Insert multiple lines of text before specific line

2019-02-09 20:25发布

I am trying to insert a few lines of text before a specific line, but keep getting sed errors when I try to add a new line character. My command looks like:

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

The error that is reported is:

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

I've tried, using \n, \\ (as in the example), no character at all, just moving the second line to the next line. I've also tried something like:

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

EDIT!: Apologies, I wanted the text inserted BEFORE the existing, not after!

8条回答
做个烂人
2楼-- · 2019-02-09 21:01

When the lines to be inserted are the result of some command "mycmd" (like cat results.txt or printf "%s\n" line{1..3}), you can do

sed -i 's/Line to insert after/r' <(cmd) file
or 
sed -i 's/Line to insert after/echo "&";cmd/e' file

The last command can be simple modified when you want to insert before some match.

查看更多
戒情不戒烟
3楼-- · 2019-02-09 21:05

To be POSIX compliant and run in OS X, I used the following (single quoted line and empty line are for demonstration purposes):

sed -i "" "/[pattern]/i\\
line 1\\
line 2\\
\'line 3 with single quotes\`
\\
" <filename>
查看更多
登录 后发表回答