Mea*_*ell 7 unix bash sed text-manipulation
我试图在特定行之前插入几行文本,但在尝试添加新行字符时不断出现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
Run Code Online (Sandbox Code Playgroud)
报告的错误是:
sed: -e expression #1, char 77: unterminated `s' command
Run Code Online (Sandbox Code Playgroud)
我试过,使用\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
Run Code Online (Sandbox Code Playgroud)
编辑!:道歉,我希望文本在现有之前插入,而不是之后!
anu*_*ava 10
这应该工作:
sed -i '/Line to insert after/ i Line one to insert \
second new line to insert \
third new line to insert' file
Run Code Online (Sandbox Code Playgroud)
对于除了单独行上的简单替换之外的任何其他内容,使用awk而不是sed以简化,清晰,稳健等等.
要在一行之前插入:
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
Run Code Online (Sandbox Code Playgroud)
要在一行之后插入:
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
Run Code Online (Sandbox Code Playgroud)