我正在学习 shell 脚本,为此我正在使用 HackerRank。sed在同一站点上有一个与此相关的问题:“Sed”命令 #1:
对于给定的输入文件的每行,变换字“的”与“这个”的第一次出现。搜索和转换应该严格区分大小写。
首先我尝试过,
sed 's/the/this/'
Run Code Online (Sandbox Code Playgroud)
但在那个示例测试用例中失败了。然后我试过了
sed 's/the /this /'
Run Code Online (Sandbox Code Playgroud)
它奏效了。那么,问题来了,这些空格产生了什么不同?我在这里错过了什么吗?
Kus*_*nda 20
这是一种廉价且容易出错的词匹配方式。
请注意,the它后面的空格不匹配 word thereby,因此匹配 afterthe避免匹配单词开头的字符串。然而,它仍然不匹配bathe(如果后面有一个空格),它并不能匹配the在一行的末尾。
为了the正确匹配单词(或任何其他单词),您不应该在单词周围使用空格,因为这会阻止您在行首或行尾匹配它,或者它的两侧是任何其他非单词字符,例如例如,任何标点符号或制表符。
相反,使用零宽度字边界模式:
sed 's/\<the\>/this/'
Run Code Online (Sandbox Code Playgroud)
在\<和\>边界前,后字相匹配,即之间的空间单词字符和非单词字符。单词字符通常是任何字符匹配[[:alnum:]_](或[A-Za-z0-9_]在 POSIX 语言环境中)。
使用 GNU sed,您还可以\b代替\<and 使用\>:
sed 's/\bthe\b/this/'
Run Code Online (Sandbox Code Playgroud)
区别在于the输入文本后是否有空格。
例如:
一个没有空格的句子,没有替换:
$ echo 'theman' | sed 's/the /this /'
theman
Run Code Online (Sandbox Code Playgroud)
带有空格的句子,按预期工作:
$ echo 'the man' | sed 's/the /this /'
this man
Run Code Online (Sandbox Code Playgroud)
对于带有另一个空格字符的句子,不会发生替换:
$ echo -e 'the\tman' | sed 's/the /this /'
the man
Run Code Online (Sandbox Code Playgroud)
sed 适用于正则表达式。使用sed 's/the /this /'您只需the在匹配模式的一部分之后留出空间。
使用sed 's/the/this/'您替换所有出现的thewith,this无论the.
在 HackerRank 练习中,结果是相同的,因为用 this 替换 the 是合乎逻辑的……您只替换默认情况下后跟空格(语法规则)的亲名词。
例如,如果您尝试the将单词大写,您会看到不同之处the theater:
echo 'the theater' |sed 's/the /THE /g'
THE theater
#theater is ignored since the is not followed by space
echo 'the theater' |sed 's/the/THE/g'
THE THEater
#both the are capitalized.
Run Code Online (Sandbox Code Playgroud)