【发布时间】:2020-08-28 16:55:17
【问题描述】:
我一直在尝试使用tr util 清理我的巨大 xml 文件 (> 6gb)。目标是去除所有无效字符,同时去除 、&、>等。
这是我当前的实现:
cat input.xml | tr -dc '[:print:]' > output.xml
但它只删除无效字符。您对如何使用tr util 来实现它有什么建议吗?
【问题讨论】:
我一直在尝试使用tr util 清理我的巨大 xml 文件 (> 6gb)。目标是去除所有无效字符,同时去除 、&、>等。
这是我当前的实现:
cat input.xml | tr -dc '[:print:]' > output.xml
但它只删除无效字符。您对如何使用tr util 来实现它有什么建议吗?
【问题讨论】:
在 Notepad++ 中打开文件并使用替换选项。
【讨论】:
字符转义是一种仅使用 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 对页面进行字符编码,所以通常不需要使用字符转义。但是,您可能会发现它们对于表示不可见或模棱两可的字符或会以不良方式与周围源代码或文本交互的字符很有用。
【讨论】:
tr 可能行不通tr 仅用于替换单个字符或字符类。您的示例 、& 和> 是字符串。我们需要另一个工具。
perl 的示例
$ cat input.xml
<xml><tag> hello&, >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
【讨论】:
.* 不贪心。我会留下我所拥有的,因为它很简洁并且确实准确地描述了整体模式。