bash 用 sed 插入单引号

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

Insert single quote with sed

bashshellsed

提问by lvthillo

I want to add some text on a line:

我想在一行上添加一些文本:

sudo sed -i '5imytext 16/16' /file

Now I've added mytext 16/16on line 5 of the file, but I actually want to add the text 'mytext' 16/16(mytextbetween single quotes).

现在我已经mytext 16/16在文件的第 5 行添加了,但我实际上想添加文本'mytext' 16/16mytext在单引号之间)。

I tried

我试过

sudo sed -i '5i'mytext' 16/16' /file

but it didn't work. Can someone help me?

但它没有用。有人能帮我吗?

采纳答案by Tom Fenech

The single quotes that you're trying to use in your insertion string are interfering with the ones around the sed command.

您尝试在插入字符串中使用的单引号会干扰 sed 命令周围的单引号。

The simplest thing to do is to use different quotes around your sed command:

最简单的方法是在 sed 命令周围使用不同的引号:

"5i'mytext' 16/16"

Normally it's best to use single quotes around a sed command but it would be more tricky in this case:

通常最好在 sed 命令周围使用单引号,但在这种情况下会更棘手:

'5i'"'"'mytext'"'"' 16/16'

Basically, you need to put the single quotes inside double quotes somehow and in this case there's no reason not to double quote the whole command.

基本上,您需要以某种方式将单引号放在双引号内,在这种情况下,没有理由不对整个命令加双引号。

As suggested by 123 in the comments, an alternative would be to put your sed command into a script file:

正如评论中的 123 所建议的,另一种方法是将 sed 命令放入脚本文件中:

5i'mytext' 16/16

Then use the -fswitch to sed:

然后使用-f开关来sed:

sed -f script

This avoids the need to use two kinds of quotes.

这避免了使用两种引号的需要。

回答by Jahid

Use double quote in these cases. Because:

在这些情况下使用双引号。因为:

  1. Single quote can't have single quote inside it. ('\''won't work)
  2. Double quote can have both single quote and double quote inside it. ("'\""will work)
  1. 单引号里面不能有单引号。('\''不会工作)
  2. 双引号可以同时包含单引号和双引号。("'\""会工作)

Example:

例子:

sudo sed -i "5i'mytext' 16/16" /file