bash sed 插入行命令 OSX

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

sed insert line command OSX

macosbashsedinsert

提问by gdavtor

I'm trying to insert text to the third line in a file using sed, and the syntax I've found on other forums is:

我正在尝试使用 sed 将文本插入文件的第三行,我在其他论坛上找到的语法是:

sed -i '' "3i\ text to insert" file

When I use this however, I get an error:

但是,当我使用它时,出现错误:

sed: 1: "3i\ text to insert": extra characters after \ at the end of i command

I can't seem to figure out what is causing the problem. I'm using OSX, which is why I have an empty ' ' as my extension.

我似乎无法弄清楚是什么导致了问题。我正在使用 OSX,这就是为什么我有一个空的 ' ' 作为我的扩展名。

Thanks!

谢谢!

回答by Tom Fenech

You should put a newline directly after the \:

您应该在 之后直接放置一个换行符\

sed '3i\
text to insert' file

This is actually the behaviour defined by the POSIX specification. The fact that GNU sed allows you to specify the text to be inserted on the same line is an extension.

这实际上是POSIX 规范定义的行为。GNU sed 允许您指定要在同一行插入的文本这一事实是一个扩展。



If for some reason you need to use double quotes around the sed command, then you must escape the backslash at the end of the first line:

如果由于某种原因您需要在 sed 命令周围使用双引号,那么您必须在第一行的末尾转义反斜杠:

sed "3i\
text to insert" file

This is because a double-quoted string is processed first by the shell, and \followed by a newline is removed:

这是因为 shell 首先处理双引号字符串,\然后删除换行符:

$ echo "abc\
def"
abcdef

回答by anubhava

On OSX you can use:

在 OSX 上,您可以使用:

sed -i.bak '3i\
text to insert
' file

回答by VladimirAus

Here's how to do it in one line syntax

以下是如何用一行语法来做到这一点

sed -i '' -e "2s/^//p; 2s/^.*/text to insert/" file
  • duplicate second line: 2s/^//p;

  • replace new line with your text: 2s/^.*/text to insert/

  • 重复第二行: 2s/^//p;

  • 用您的文本替换新行: 2s/^.*/text to insert/

回答by ali

This works for me

这对我有用

sed -i '' '3i\
text to insert' file 

回答by Joe Bowbeer

A one-liner for OSX employing ANSI-C quoting:

使用 ANSI-C 引用的 OSX 单行:

sed -i '' '3i\'$'\n''text to insert' file

Adapted from https://stackoverflow.com/a/24299845/901597

改编自https://stackoverflow.com/a/24299845/901597

回答by Hector Quemada

I've found that I have to insert a \ at the end of the line to be inserted, otherwise it concatenates it at the beginning of the original line. So, if I want to insert a new third line,...

我发现我必须在要插入的行的末尾插入一个 \ ,否则它会在原始行的开头连接它。所以,如果我想插入一个新的第三行,...

sed -i '' '3i\<br>
New line to be inserted.\<br>
' file

回答by Anil

If you want to modify a file of specific file type(.sh in my case) use this command.

如果要修改特定文件类型的文件(在我的情况下为 .sh),请使用此命令。

sed -i '.sh' '3i\
mymodified text to insert' temp.sh

Make sure you have line break after slash ("\")

确保在斜杠(“\”)后有换行符