是的,它的预期行为为awk。当您在第一个脚本中运行 sub("\\", "\\\\") 时,在 sub 的内部 "(双引号)中,因为我们没有使用 / 匹配模式,我们需要先转义 \(实际文字字符)然后为了转义,我们使用\,所以我们也需要转义它,因此它将变为\\\\
\\ \\
| |
| |
first 2 chars are denoting escaping next 2 chars are denoting actual literal character \
您的第一种情况没有发生,因此没有匹配,因此没有替换,在您的第二个 awk 脚本中,您正在执行此操作(在 sub 的正则表达式匹配部分中转义部分),因此它完美匹配 \。
让我们通过示例来看看这个,并尝试将... 用于检查目的。
什么都没有发生时:因为没有匹配到
awk '{sub("\\", "....\\\\"); print $0}' Input_file
d:\
发生模式匹配时:
awk '{sub("\\\\", "...\\\\"); print $0}' Input_file
d:...\\
来自man awk:
gsub(r, s [, t])
For each substring matching the regular expression r in the string t,
substitute the string s, and return the number of substitutions.
我们如何才能执行实际的转义部分(我们只需要在字符前使用一次 \)? 请在 /../ 中提及您的正则表达式在sub 的第一部分中,我们不需要在这里双重转义\。
awk '{sub(/\\/,"&\\")} 1' Input_file