[英]How does escaping a literal dot work for sed
The following sed
command以下sed
命令
echo '.' | sed "s/\\./foo/"
substitutes .
替代品.
with foo
, as expected.正如预期的那样,使用foo
。 However, if we escape the non-alphanumeric .
但是,如果我们转义非字母数字的.
in the above command在上面的命令中
echo '.' | sed "s/\\\./foo/"
prints barely .
几乎没有打印.
, whereas foo
is expected. , 而foo
是预期的。 sed
should match the character .
sed
应该匹配字符.
literally, but it doesn't.从字面上看,但事实并非如此。 I cannot understand what is happening with the dot.我无法理解点发生了什么。 I believe that I should simply put a backslash in front of every non-alphanumeric character in bash, if a string is double-quoted.如果字符串被双引号括起来,我相信我应该在 bash 中的每个非字母数字字符前面简单地放一个反斜杠。 A dot is a non-alphanumeric character so what is wrong about escaping it and why does it produce a different result?点是非字母数字字符,那么 escaping 有什么问题,为什么会产生不同的结果?
This is because how backslashes work in bash double quote "
escaping.这是因为反斜杠在 bash 双引号"
escaping”中的工作方式。
echo "\\"
\
echo "\."
\.
echo "s/\\./foo/"
s/\./foo/
echo "s/\\\./foo/"
s/\\./foo/
From man bash
:来自man bash
:
Within double quotes, the backslash retains its special meaning only when
followed by one of the following characters: $, `, ", \,or <newline>.
So in the first case, sed gets s/\./foo/
and interprets it as "replace a dot with foo".所以在第一种情况下,sed 得到s/\./foo/
并将其解释为“用 foo 替换点”。 In the second case sed gets s/\\./foo/
and interprets it as "replace a backslash and one other character with foo.在第二种情况下,sed 获取s/\\./foo/
并将其解释为“用 foo 替换反斜杠和另一个字符。
You better use single quote escaping in this case:在这种情况下,您最好使用单引号 escaping :
echo 's/./foo/'
s/./foo/
echo 's/\./foo/'
s/\./foo/
which is probably what you wanted.这可能是你想要的。
In your second one, the .
在你的第二个中, .
is still a literal dot, but the regular expression only replaces the two-character sequence \.
仍然是文字点,但正则表达式仅替换两个字符序列\.
(not .
by itself) with foo
: (不是.
本身)与foo
:
$ echo '=\.=' | sed "s/\\\./foo/"
=foo=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.