2015-08-14 374 views
4

我想在特定行之前插入几行文本,但在尝试添加新行字符时仍然出现sed错误。我的命令看起来像:在使用sed的特定行之前插入多行文本

sed -r -i '/Line to insert after/ i Line one to insert \\ 
    second new line to insert \\ 
    third new line to insert' /etc/directory/somefile.txt 

所报告的错误是:

sed: -e expression #1, char 77: unterminated `s' command 

我尝试使用\n\\(如上例),无字可言,只是移动第二行到下一行。我也试过类似的东西:

sed -r -i -e '/Line to insert after/ i Line one to insert' 
    -e 'second new line to insert' 
    -e 'third new line to insert' /etc/directory/somefile.txt 

编辑!:道歉,我希望在现有的文本之前插入,而不是之后!

回答

6

这应该工作:

sed -i '/Line to insert after/ i Line one to insert \ 
second new line to insert \ 
third new line to insert' file 
+1

可能想,如果你使用了''插入后 – 123

+0

是的,这是正确的。 – anubhava

+1

绝佳的指南。非常感谢@anubhava –

0
sed -i '/Line to insert after/ i\ 
Line one to insert\ 
second new line to insert\ 
third new line to insert' /etc/directory/somefile.txt 
+0

也许你应该解释一下你的改变。 – drescherjm

0

这可能会为你工作(GNU sed的&击):

sed -i $'/Line to insert after/a\line1\\nline2\\nline3' file 
3

对于除个别线路简单替代其他任何东西,用awk代替为了简单,清晰,鲁棒性等等等等。

要插入之前行:

awk ' 
{ print } 
/Line to insert after/ { 
    print "Line one to insert" 
    print "second new line to insert" 
    print "third new line to insert" 
} 
' /etc/directory/somefile.txt 
0

这LL从第一行。对于如作品:如果你想从一个文件中的第三行插入,替换“1I

awk ' 
/Line to insert before/ { 
    print "Line one to insert" 
    print "second new line to insert" 
    print "third new line to insert" 
} 
{ print } 
' /etc/directory/somefile.txt 

要在行后面插入“到”3i“。

sed -i '1i line1'\\n'line2'\\n'line3' 1.txt 

cat 1.txt 

line1 
line2 
line3 
Hai 
0

符合POSIX标准,并在OS X上运行,我用下面的(单引号线和空行是用于演示):

sed -i "" "/[pattern]/i\\ 
line 1\\ 
line 2\\ 
\'line 3 with single quotes\` 
\\ 
" <filename> 
相关问题