SED语法在两个行号之间插入字符串?

SED语法在两个行号之间插入字符串?,sed,Sed,例如,在文本文件/location/file.txt中: some random text some more random text some more random text 我想在第二行之间插入一串单词。在2和3之间插入两个单词(在2之后): 要在1和2之间插入(在2之前): 或者,如果您不想要换行符: sed '2a\\ttwo words' input 使用awk: awk '{print} NR==2{print "here is some extra text after li

例如,在文本文件/location/file.txt中:

some random text
some more random text
some more random text

我想在第二行之间插入一串单词。

在2和3之间插入两个单词(在
2
之后):

要在1和2之间插入(在
2
之前):

或者,如果您不想要换行符:

sed '2a\\ttwo words' input
使用awk:

awk '{print} NR==2{print "here is some extra text after line 2"}' file
如果要覆盖原始文件,请执行以下操作:

awk '{print} NR==2{print "here is some extra text after line 2"}' file > tmp && mv tmp file
这将在第二行和第三行之间添加一行“newline here”

awk 'NR==3{print "new line here"}1' your_file
如果你想在原地做,就用 perl:


输入更改为/path/file.txt?是的,如果您想进行就地替换,请添加
-i
选项sed'36{a\two words}'/var/www/mysite/test.php,出现错误您需要在
a\
之后和
}
之前有一个换行符,如上面的示例所示。我只能从单个命令使用sed,然后必须在下一个命令之前再次运行它,是否有包含新行的语法?我是说我不能回去了。
awk '{print} NR==2{print "here is some extra text after line 2"}' file > tmp && mv tmp file
awk 'NR==3{print "new line here"}1' your_file
perl -pi -e 'print "new line here.\n" if($.==3)' your_file