您可以在sed中使用哪些定界符? [英] What delimiters can you use in sed?
问题描述
我们通常会看到人们抱怨当他们想使用 sed
中的s'错误的错误时,包含
sed
分隔符的模式。
We normally see people complaining about the unknown option to s'
error in sed
when they want to use a pattern that contains the sed
delimiter.
例如,如果我们使用 /
:
$ var="hel/lo"
$ sed "s/a/$var/g" <<< "haha"
sed: -e expression #1, char 9: unknown option to `s'
的未知选项
因此,我们建议使用其他定界符,例如 |
:
$ sed "s|a|$var|g" <<< "haha"
hhel/lohhel/lo
但是,我想知道可能的分隔符 sed
可以接受...因为它似乎几乎是任何字符,包括类似于正则表达式的字符( *
, ?
,。
,...)!
However, I want to know what are the possible delimiters sed
can accept... since it seems to be almost any character including regex-like ones (*
, ?
, .
, ...)!
在我的 sed(GNU sed)4.2.2
中:
$ sed 's/a/b/g' <<< "haha"
hbhb
$ sed 's_a_b_g' <<< "haha"
hbhb
$ sed 's#a#b#g' <<< "haha"
hbhb
$ sed 's$a$b$g' <<< "haha"
hbhb
$ sed 's?a?b?g' <<< "haha"
hbhb
$ sed 's*a*b*g' <<< "haha"
hbhb
$ sed 's-a-b-g' <<< "haha"
hbhb
$ sed 's.a.b.g' <<< "haha"
hbhb
$ sed 'sXaXbXg' <<< "haha"
hbhb
$ sed 'sxaxbxg' <<< "haha"
hbhb
$ sed 's1a1b1g' <<< "haha"
hbhb
甚至 a
如果已转义,可以在这里工作:
Even a
works here if it is escaped:
$ sed 'saaabag' <<< "haha"
sed: -e expression #1, char 5: unknown option to `s'
$ sed 'sa\aabag' <<< "haha"
hbhb
对此是否有规范?
推荐答案
也许是最接近标准的POSIX / IEEE开放组基础规范说:
Perhaps the closest to a standard, the POSIX/IEEE Open Group Base Specification says:
[2addr] s / BRE / replacement / flags
在
模式空间中用BRE实例替换替换字符串。 除反斜杠或换行符之外的任何其他字符都可以使用
代替斜杠来分隔BRE和替换行。
在BRE及其替换中,如果BRE分隔符本身以反斜杠开头,则可以将
用作文字字符。
Substitute the replacement string for instances of the BRE in the pattern space. Any character other than backslash or newline can be used instead of a slash to delimit the BRE and the replacement. Within the BRE and the replacement, the BRE delimiter itself can be used as a literal character if it is preceded by a backslash."
这篇关于您可以在sed中使用哪些定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!