使用 sed,在模式上方或下方插入一行?

我需要编辑大量的文件,通过插入一行或多行,无论是在一个唯一的模式的正下方还是正上方。请建议如何做到这一点使用 sedawkperl(或其他任何东西)在一个外壳。谢谢!例如:

some text
lorem ipsum dolor sit amet
more text

我想在 lorem ipsum dolor sit amet之后插入 consectetur adipiscing elit,这样输出文件看起来像:

some text
lorem ipsum dolor sit amet
consectetur adipiscing elit
more text
206497 次浏览

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
pattern
line1 line2

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
line1 line2
pattern

The following adds one line after SearchPattern.

sed -i '/SearchPattern/aNew Text' SomeFile.txt

It inserts New Text one line below each line that contains SearchPattern.

To add two lines, you can use a \ and enter a newline while typing New Text.

POSIX sed requires a \ and a newline after the a sed function. [1] Specifying the text to append without the newline is a GNU sed extension (as documented in the sed info page), so its usage is not as portable.

[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
/bin/ed $filename