如何轻松地从 Linux 中的标准输入流转换 HTML 特殊实体?

Mik*_*e B 12 scripting linux bash html sed

CentOS

有没有一种简单的方法可以从数据流中转换 HTML 特殊实体?我将数据传递给 bash 脚本,有时该数据包含特殊实体。例如:

“测试”& 测试 $ 测试!测试@#$%^& *

我不确定为什么有些字符显示正常而其他字符显示不正常,但不幸的是,我无法控制传入的数据。

我想我可以在这里使用 SED,但这似乎很麻烦,并且可能容易出现误报。是否有我可以通过管道传输的 Linux 命令专门用于解码此类数据?

Jas*_*Tan 14

Perl(一如既往)是您的朋友。我认为这会做到:

perl -n -mHTML::Entities -e ' ; print HTML::Entities::decode_entities($_) ;'
Run Code Online (Sandbox Code Playgroud)

例如:

echo '"test" & test $test ! test @ # $ % ^ & *' |perl -n -mHTML::Entities -e ' ; print HTML::Entities::decode_entities($_) ;'
Run Code Online (Sandbox Code Playgroud)

有输出:

someguy@somehost ~]$ echo '"test" & test $test ! test @ # $ % ^ & *' |perl -n -mHTML::Entities -e ' ; print HTML::Entities::decode_entities($_) ;'
"test" & test $test ! test @ # $ % ^ & *
Run Code Online (Sandbox Code Playgroud)


Mic*_*ton 9

PHP 非常适合这一点。此示例需要 PHP 5:

cat file.html | php -R 'echo html_entity_decode($argn);'
Run Code Online (Sandbox Code Playgroud)


Ski*_*rou 8

recode似乎在主要 GNU/Linux 发行版的默认软件包存储库中可用。例如将 HTML 实体解码为 UTF-8 :

…|recode html..utf8
Run Code Online (Sandbox Code Playgroud)


小智 5

使用 Python 3:

python3 -c 'import html,sys; print(html.unescape(sys.stdin.read()), end="")' < file.html
Run Code Online (Sandbox Code Playgroud)