4

I want to insert a line between two lines, only if the second line matches a certain pattern

for example the input file is as follows:

pattern (match 1, line 1)
line 2
line 3
line 4
line 5 (before pattern)
pattern (match 2, line 5)
line 7
line 8
line 9
line 10 (before pattern)
pattern (match 3, line 11)
line 12

I want to insert lineToInsert between line 5 and pattern and between line 10 and pattern

I have tried this command:

sed 'N;s/\n\(pattern\)/\n\ 
lineToInsert\n\1/'

I expect this to work, but it only works if the matched pattern exists on an even line only !!

So, How could I achieve this using sed or any other tool / command? and Why the previous command does not work ?

4

4 回答 4

3

使用 awk 您可以执行以下操作:

awk 'NR>1&&/pattern/{print "lineToInsert"}1' file
于 2013-09-22T20:20:10.790 回答
3

sed有一个插入命令

sed '1n; /^pattern/i line to insert'
于 2013-09-22T21:05:01.893 回答
2

This might work for you (GNU sed):

sed -e '$!N;/\npattern/a\insert line' -e 'P;D' file

This reads 2 lines into the pattern space and then looks for the pattern at the beginning of the second line. If it finds the pattern it appends the new line to the first line. At all times it prints the first line and then deletes it thus invoking the $!N without reading in a new line automatically as sed normally does. The D command overides the automatic reading in of a new line when a newline (\n) exists already in the pattern space.

Because you were not using the P;D combination you were always reading lines in two at a time.

Of course this can easier be handled using:

sed '1n;/^pattern/i\insert new line' file # as in Glen Jackman's answer
于 2013-09-23T08:28:11.743 回答
2

您已经有了一些解决方案,但是,为什么您的解决方案不起作用?因为读取每一行并N读取下一行并将其附加到当前行。因此,您将每对两行保存到缓冲区中,并将替换命令应用于它们并用换行符连接。

执行N命令后的缓冲区将是:

pattern\nline 2

之后:

line 3\nline 4

之后:

line 5 \npattern

等等。

在您的替换命令中,您在模式之前有一个换行符,因此只有pattern在第二行中才会成功,或者换一种说法,偶数。

使用,您可以避免N和逐行处理文件,而不必担心换行符,例如:

sed '1! s/\(pattern\)/lineToInsert\n\1/' infile

它产生:

pattern 
line 2
line 3
line 4
line 5 
lineToInsert
pattern 
line 7
line 8
line 9
line 10 
lineToInsert
pattern 
line 12
于 2013-09-22T20:38:48.957 回答