出现点和下划线时搜索并替换为 sed

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6123915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:57:03  来源:igfitidea点击:

Search and replace with sed when dots and underscores are present

linuxcommand-linesed

提问by algorithmicCoder

How do I replace foo. with foo_ with sed simply running

我如何替换 foo. 与 foo_ 与 sed 简单地运行

sed 's/foo./foo_/g' file.php

doesn't work. Thanks!

不起作用。谢谢!

回答by rid

Escape the .:

逃脱.

sed 's/foo\./foo_/g' file.php

Example:

例子:

~$ cat test.txt 
foo.bar
~$ sed 's/foo\./foo_/g' test.txt 
foo_bar

回答by August Karlstrom

You need to escape the dot - an unescaped dot will match any character after foo.

您需要对点进行转义 - 未转义的点将匹配 foo 之后的任何字符。

sed 's/foo\./foo_/g'

回答by sashang

Escape the dot with a \

用 \ 转义点

sed 's/foo\./foo_/g' file.php

If you find the combination of / and \ confusing you can use another 'separator' character

如果您发现 / 和 \ 的组合令人困惑,您可以使用另一个“分隔符”字符

sed 's#foo\.#foo_#g

The 2nd character after the s can be anything and sed will use that character as a separator.

s 之后的第二个字符可以是任何字符,sed 将使用该字符作为分隔符。

回答by Paul S

Interestingly, if you want to search for and replace just the dot, you have to put the dot in a character set. Escaping just the dot alone in a sed command for some reason doesn't work. The dot is still expanded to a single character wild card.

有趣的是,如果您只想搜索和替换点,则必须将点放入字符集中。由于某种原因,仅在 sed 命令中单独转义点是行不通的。点仍然扩展为单个字符通配符。

$ bash --version  # Ubuntu Lucid (10.04)

GNU bash, version 4.1.5(1)-release (x86_64-pc-linux-gnu)

GNU bash,版本 4.1.5(1)-release (x86_64-pc-linux-gnu)

$ echo aa.bb.cc | sed s/\./-/g  # replaces all characters with dash

'--------'

'--------'

$ echo aa.bb.cc | sed s/[.]/-/g  # replaces the dots with a dash

aa-bb-cc

aa-bb-cc

With the addition of leading characters in the search, the escape works.

通过在搜索中添加前导字符,转义符起作用了。

$ echo foo. | sed s/foo\./foo_/g  # works

foo_

foo_

Putting the dot in a character set of course also works.

将点放在字符集中当然也有效。

$ echo foo. | sed s/foo[.]/foo_/g  # also works

foo_

foo_

-- Paul

——保罗

回答by jfg956

For myself, sed 's/foo\./foo_/g'is working. But you can also try:

对于我自己,sed 's/foo\./foo_/g'正在工作。但你也可以尝试:

sed -e 's/foo\./foo_/g'

and

sed -e "s/foo\./foo_/g"

and

sed 's/foo[.]/foo_/g'