Linux 如何使用 SED 替换文件内的撇号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18119433/
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-07 00:29:51  来源:igfitidea点击:

How to replace to apostrophe ' inside a file using SED

linuxunixsed

提问by neversaint

I have a file "test.txt" that contain the following

我有一个包含以下内容的文件“test.txt”

+foo+
+bar+

What I want to do is to replace them into:

我想要做的是将它们替换为:

'foo'
'bar'

But why this code doesn't work?

但是为什么这段代码不起作用?

sed  's/\+/\'/' test.txt

What's the right way to do it?

正确的做法是什么?

采纳答案by falsetru

Use "instead. And add gflag to replace all.

使用"来代替。并添加g标志以替换所有内容。

sed  "s/\+/\'/g" test.txt

回答by anubhava

+is not a special character without -rswitch in sed. You can run the substitute command without any escaping:

+不是没有-r切换到 sed的特殊字符。您可以在不进行任何转义的情况下运行替换命令

echo '+foo+' | sed "s/+/'/g"

# output: 'foo'

If you want to save changed file then use:

如果要保存更改的文件,请使用:

sed -i.bak "s/+/'/g" test.txt

回答by devnull

You can also replace all instances of +with 'in the file by using tr:

您也可以替换的所有实例+'使用该文件中tr

tr '+' "'" < inputfile

回答by potong

This might work for yoyu (GNU sed):

这可能适用于 yoyu (GNU sed):

sed 'y/+/'\''/' file