为什么备用分隔符不适用于 sed -e '/pattern/s/a/b/'? [英] Why do alternate delimiters not work with sed -e '/pattern/s/a/b/'?
问题描述
这里有一些我发现没有意义的东西.
Here is something I have discover that doesn't make sense.
cat config.h
的输出:
define somevar foo // Sample variable
此版本的命令用于将 foo 更改为 bar 并保留注释:
This version of the command works to change foo to bar and preserve the comments:
sed -e '/somevar/s/foo/bar/' config.h
这不起作用:
sed -e '|somevar|s|foo|bar|' config.h
出现此错误:
sed:-e 表达式 #1,字符 1:未知命令:`|'
sed: -e expression #1, char 1: unknown command: `|'
有趣的是,这确实有效:
Funnily enough this does work:
sed -e '/somevar/s|foo|bar|' config.h
也许我遗漏了文档的某些部分.在同一个 sed 命令中使用两个不同的分隔符似乎很奇怪.
Perhaps I am missing some part of the documentation. It seems very odd to have two different delimiters in the same sed command.
错误或功能?
推荐答案
这会起作用:
sed -e '\|somevar|s|foo|bar|'
GNU sed 的 man
页面对此非常清楚:
The man
page of GNU sed is pretty clear about this:
/regexp/
Match lines matching the regular expression regexp.
\cregexpc
Match lines matching the regular expression regexp. The c may
be any character.
即c
可以是任意字符,但\
是必须的.
That is, the c
may be any character, but the starting \
is mandatory.
我周围没有 FreeBSD,但根据 @bonsaivikingman
页面里面也很清楚:
I don't have a FreeBSD around, but according to @bonsaiviking the man
page there is also very clear:
开头分隔符前面需要有反斜杠,除非它是斜杠.
The opening delimiter needs to be preceded by a backslash unless it is a slash.
另一方面,在 OSX 中,这一点都不清楚:
On the other hand in OSX this is not clear at all:
In a context address, any character other than a backslash (``\'')
or newline character may be used to delimit the regular expression.
Also, putting a backslash character before the delimiting character
causes the character to be treated literally. For example, in the
context address \xabc\xdefx, the RE delimiter is an ``x'' and the
second ``x'' stands for itself, so that the regular expression is
``abcxdef''.
请注意,那里的示例使用了 \xpatternx
而不是 xpatternx
.这就是它给出的所有线索,它并没有说明 xpatternx
不起作用.
Notice that the example there uses \xpatternx
instead of just xpatternx
. That's all the clue it gives, it doesn't make it clear that xpatternx
won't work.
基于 @that-other-guy 的论点,sed
(以及@Birei 指出的perl
等其他语言)需要这个正确工作的额外线索.
Based on the argument of @that-other-guy, it makes sense that sed
(and other languages like perl
as @Birei pointed out) need this extra clue to work correctly.
这篇关于为什么备用分隔符不适用于 sed -e '/pattern/s/a/b/'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!