使用sed,在图案上方或下方插入一行? [英] Using sed, Insert a line above or below the pattern?
问题描述
我需要编辑大量文件,方法是在唯一模式的下方或上方插入一行或多行.请告知如何在外壳中使用sed
,awk
,perl
(或其他任何方式)进行操作.谢谢!示例:
I need to edit a good number of files, by inserting a line or multiple lines either right below a unique pattern or above it. Please advise on how to do that using sed
, awk
, perl
(or anything else) in a shell. Thanks! Example:
some text
lorem ipsum dolor sit amet
more text
我想在lorem ipsum dolor sit amet
之后插入consectetur adipiscing elit
,所以输出文件将如下所示:
I want to insert consectetur adipiscing elit
after lorem ipsum dolor sit amet
, so the output file will look like:
some text
lorem ipsum dolor sit amet
consectetur adipiscing elit
more text
推荐答案
在模式后追加:( -i用于就地替换). line1和line2是您要附加(或添加)的行
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
输出:
#cat inputfile
pattern
line1 line2
要在以下行之前添加行:
To prepend the lines before:
sed -i '/pattern/i \
line1 \
line2' inputfile
输出:
#cat inputfile
line1 line2
pattern
这篇关于使用sed,在图案上方或下方插入一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!