2015-08-14 414 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> 
相關問題