如何从文件中删除特殊符号,如 &?

问题描述 投票:0回答:2

我一直在尝试清理我的巨大的xml文件(> 6gb),并使用 tr 利用。的目标是去除所有无效字符,同时也要去除诸如  , &, > 等等。

这是我目前的实现。

cat input.xml | tr -dc '[:print:]' > output.xml

但它只能删除无效的字符 你有什么建议吗?tr 利用?

bash unix sed tr
2个回答
1
投票

tr 可能不会成功

tr 只用于替换单个字符或字符类。你的例子  , &> 是字符串。我们需要另一个工具。

下面是一个例子 perl

$ cat input.xml
<xml><tag>&nbsp;hello&amp;, &gt;world!</tag></xml>
$ cat input.xml | perl -p -e 's/&.*?;//g'
<xml><tag>hello, world!</tag></xml>

解释。

perl -p -e 's/&.*?;//g'

perl -------------------- Run a perl program
     -p ----------------- Sets up a loop around our program
        -e -------------- Use what comes next as a line of our program
           's/&.*?;//g' - Our program, which is a perl regular expression.
                        - Explanation below:


           ' ------------ Quotes prevent shell expansion/interpolation.
            s ----------- Start a string substitution.
             / ---------- Use '/' as the command separator.
              & --------- Matches literal ampersand (&),
               . -------- followed by any character (.),
                * ------- any number of times (*),
                 ?; ----- until the next semicolon (?;).
                   // --- Replaces the matching text with the characters between the slashes (i.e. nothing at all)
                     g -- Allows matching the pattern multiple times per line
                      ' - Quotes prevent shell expansion/interpolation

请注意,我假设的模式是[AMPERSAND(&), SOMETHING, SEMICOLON(;)]根据你提供的示例字符串。

你可以扩展那个程序来删除你的无效字符,但我还是会继续使用 tr 的。至少在我的系统上是比较快的。

所以,把它放在一起,你会得到

cat input.xml | perl -p -e 's/&.*?;//g' | tr -dc '[:print:]' > output.xml

0
投票

在Notepad++中打开文件并使用替换选项。


0
投票

字符转义是一种在源代码中仅使用ASCII字符表示字符的方式。在HTML中,你可以用以下方式转义欧元符号€。

Format  Name
&#x20AC;    hexadecimal numeric character reference
&#8364; decimal numeric character reference
&euro;  named character reference

在CSS语法中,你可以使用以下方式之一。

Format  Notes
\20AC   must be followed by a space if the next character is one of a-f, A-F, 0-9
\0020AC must be 6 digits long, no space needed (but can be included)

后面的空格会被视为转义符的一部分,所以如果你真的想在转义符后面加上空格,请使用两个空格。如果在CSS标识符中使用转义符,请参见下面的附加规则。

因为你应该使用UTF-8作为页面的字符编码,所以你通常不需要使用字符转义符。然而,您可能会发现它们对于表示不可见的或含糊不清的字符或字符很有用,否则它们会以不理想的方式与周围的源代码或文本交互。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.