your programing

HTML 엔티티에서 문자로 변환하는 Bash 스크립트

lovepro 2020. 12. 26. 16:19
반응형

HTML 엔티티에서 문자로 변환하는 Bash 스크립트


이것을 돌리는 방법을 찾고 있습니다.

hello < world

이에:

hello < world

sed를 사용할 수는 있지만 비밀 정규식을 사용하지 않고 어떻게 수행 할 수 있습니까?


레코딩을 시도하십시오 ( 아카이브 된 페이지 , GitHub 미러 , 데비안 페이지 ) :

$ echo '&lt;' |recode html..ascii
<

Linux 및 유사한 Unix-y 시스템에 설치 :

$ sudo apt-get install recode

다음을 사용하여 Mac OS에 설치합니다.

$ brew install recode

Perl 사용 :

cat foo.html | perl -MHTML::Entities -pe 'decode_entities($_);'

명령 줄에서 PHP로 :

cat foo.html | php -r 'while(($line=fgets(STDIN)) !== FALSE) echo html_entity_decode($line, ENT_QUOTES|ENT_HTML401);'

대안은 다음과 같은 웹 브라우저를 통해 파이프하는 것입니다.

echo '&#33;' | w3m -dump -T text/html

이것은 배포판을 다운로드하고 설치하는 것이 어려운 cygwin에서 나를 위해 잘 작동했습니다.

이 답변은 여기 에서 찾았 습니다.


xmlstarlet 사용 :

echo 'hello &lt; world' | xmlstarlet unesc

이 답변은 다음을 기반으로합니다. Bash에서 HTML을 이스케이프하는 짧은 방법? wgetStack Exchange에서 답변을 얻고 (사용하여 ) HTML을 일반 ASCII 문자로 변환 하는 데 잘 작동합니다 .

sed 's/&nbsp;/ /g; s/&amp;/\&/g; s/&lt;/\</g; s/&gt;/\>/g; s/&quot;/\"/g; s/#&#39;/\'"'"'/g; s/&ldquo;/\"/g; s/&rdquo;/\"/g;'

편집 1 : 2017 년 4 월 7 일-왼쪽 큰 따옴표 및 오른쪽 큰 따옴표 변환이 추가되었습니다. 이것은 SE 답변을 웹 스크랩하고 로컬 코드 파일과 비교하는 bash 스크립트의 일부입니다. Ask Ubuntu-로컬 파일 간의 코드 버전 제어 및 Ubuntu 답변 요청


2017 년 6 월 26 일 수정

를 사용하면 sedAsk Ubuntu / Stack Exchange의 1K 라인 파일에서 HTML을 ASCII로 변환하는 데 3 초 정도 걸립니다. 따라서 Bash 내장 검색을 사용하고 ~ 1 초의 응답 시간을 대체해야했습니다.

기능은 다음과 같습니다.

#-------------------------------------------------------------------------------
LineOut=""      # Make global
HTMLtoText () {
    LineOut=$1  # Parm 1= Input line
    # Replace external command: Line=$(sed 's/&amp;/\&/g; s/&lt;/\</g; 
    # s/&gt;/\>/g; s/&quot;/\"/g; s/&#39;/\'"'"'/g; s/&ldquo;/\"/g; 
    # s/&rdquo;/\"/g;' <<< "$Line") -- With faster builtin commands.
    LineOut="${LineOut//&nbsp;/ }"
    LineOut="${LineOut//&amp;/&}"
    LineOut="${LineOut//&lt;/<}"
    LineOut="${LineOut//&gt;/>}"
    LineOut="${LineOut//&quot;/'"'}"
    LineOut="${LineOut//&#39;/"'"}"
    LineOut="${LineOut//&ldquo;/'"'}" # TODO: ASCII/ISO for opening quote
    LineOut="${LineOut//&rdquo;/'"'}" # TODO: ASCII/ISO for closing quote
} # HTMLtoText ()

파이썬 3.2 이상 버전 :

cat foo.html | python3 -c 'import html, sys; [print(html.unescape(l), end="") for l in sys.stdin]'

모든 유니 코드 코드 포인트에는 최소한 두 개의 해당 HTML 엔티티가 있기 때문에 sed 대체만으로 모든 HTML 엔티티의 이스케이프 해제를 지원하려면 실용적인 명령 목록이 너무 길어야합니다.

그러나 sed, grep, Bourne 쉘 및 기본 UNIX 유틸리티 (GNU coreutils 또는 동급) 만 사용하여 수행 할 수 있습니다.

#!/bin/sh

htmlEscDec2Hex() {
    file=$1
    [ ! -r "$file" ] && file=$(mktemp) && cat >"$file"

    printf -- \
        "$(sed 's/\\/\\\\/g;s/%/%%/g;s/&#[0-9]\{1,10\};/\&#x%x;/g' "$file")\n" \
        $(grep -o '&#[0-9]\{1,10\};' "$file" | tr -d '&#;')

    [ x"$1" != x"$file" ] && rm -f "$file"
}

htmlHexUnescape() {
    printf -- "$(
        sed 's/\\/\\\\/g;s/%/%%/g
            ;s/&#x\([0-9a-fA-F]\{1,8\}\);/\&#x0000000\1;/g
            ;s/&#x0*\([0-9a-fA-F]\{4\}\);/\\u\1/g
            ;s/&#x0*\([0-9a-fA-F]\{8\}\);/\\U\1/g' )\n"
}

htmlEscDec2Hex "$1" | htmlHexUnescape \
    | sed -f named_entities.sed

그러나 GNU 유틸리티와 같은 printf 구현 \uHHHH\UHHHHHHHH시퀀스가 필요합니다. 테스트하려면, 그 예를 들어 확인 printf "\u00A7\n"인쇄 §. 셸 내장 대신 유틸리티를 호출하려면의 항목을 printf바꿉니다 env printf.

이 스크립트는 named_entities.sed명명 된 엔티티를 지원하기 위해 추가 파일을 사용합니다 . 다음 HTML 페이지를 사용하여 사양에서 생성 할 수 있습니다.

<!DOCTYPE html>
<head><meta charset="utf-8" /></head>
<body>
<p id="sed-script"></p>
<script type="text/javascript">
  const referenceURL = 'https://html.spec.whatwg.org/entities.json';

  function writeln(element, text) {
    element.appendChild( document.createTextNode(text) );
    element.appendChild( document.createElement("br") );
  }

  (async function(container) {
    const json = await (await fetch(referenceURL)).json();
    container.innerHTML = "";
    writeln(container, "#!/usr/bin/sed -f");
    const addLast = [];
    for (const name in json) {
      const characters = json[name].characters
        .replace("\\", "\\\\")
        .replace("/", "\\/");
      const command = "s/" + name + "/" + characters + "/g";
      if ( name.endsWith(";") ) {
        writeln(container, command);
      } else {
        addLast.push(command);
      }
    }
    for (const command of addLast) { writeln(container, command); }
  })( document.getElementById("sed-script") );
</script>
</body></html>

Simply open it in a modern browser, and save the resulting page as text as named_entities.sed. This sed script can also be used alone if only named entities are required; in this case it is convenient to give it executable permission so that it can be called directly.

Now the above shell script can be used as ./html_unescape.sh foo.html, or inside a pipeline reading from standard input.

For example, if for some reason it is needed to process the data by chunks (it might be the case if printf is not a shell built-in and the data to process is large), one could use it as:

nLines=20
seq 1 $nLines $(grep -c $ "$inputFile") | while read n
    do sed -n "$n,$((n+nLines-1))p" "$inputFile" | ./html_unescape.sh
done

Explanation of the script follows.

There are three types of escape sequences that need to be supported:

  1. &#D; where D is the decimal value of the escaped character’s Unicode code point;

  2. &#xH; where H is the hexadecimal value of the escaped character’s Unicode code point;

  3. &N; where N is the name of one of the named entities for the escaped character.

The &N; escapes are supported by the generated named_entities.sed script which simply performs the list of substitutions.

The central piece of this method for supporting the code point escapes is the printf utility, which is able to:

  1. print numbers in hexadecimal format, and

  2. print characters from their code point’s hexadecimal value (using the escapes \uHHHH or \UHHHHHHHH).

The first feature, with some help from sed and grep, is used to reduce the &#D; escapes into &#xH; escapes. The shell function htmlEscDec2Hex does that.

The function htmlHexUnescape uses sed to transform the &#xH; escapes into printf’s \u/\U escapes, then uses the second feature to print the unescaped characters.

ReferenceURL : https://stackoverflow.com/questions/5929492/bash-script-to-convert-from-html-entities-to-characters

반응형