【问题标题】:How do I remove special symbols such as   & from the file?如何从文件中删除特殊符号,例如 &?
【发布时间】:2020-08-28 16:55:17
【问题描述】:

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

这是我当前的实现:

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

但它只删除无效字符。您对如何使用tr util 来实现它有什么建议吗?

【问题讨论】:

    标签: bash unix sed tr


    【解决方案1】:

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

    【讨论】:

    • xml 很大(> 6GB),不可能。
    【解决方案2】:

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

    Format  Name
    €    hexadecimal numeric character reference
    € decimal numeric character reference
    €  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)
    

    尾随空格被视为转义的一部分,因此如果您确实想在转义字符后面加上空格,请使用 2 个空格。如果在 CSS 标识符中使用转义符,请参阅下面的附加规则。

    因为您应该使用 UTF-8 对页面进行字符编码,所以通常不需要使用字符转义。但是,您可能会发现它们对于表示不可见或模棱两可的字符或会以不良方式与周围源代码或文本交互的字符很有用。

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

      • "?; ----- 直到下一个分号 (?;)。"这可能不是描述正在发生的事情的最佳方式。问号使.* 不贪心。我会留下我所拥有的,因为它很简洁并且确实准确地描述了整体模式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2021-04-15
      • 2021-07-15
      • 1970-01-01
      相关资源
      最近更新 更多