sed: working with multiple lines

Got another sed question :slight_smile:

My text block is

I need to do the following:
If (and only if) the line starting with 10002,11 is followed by a line starting with 10004,9 , insert the line 10003,9 between the 2

Thus, my output should be

I tried

but this gives me

(the order is not as i wanted it)

What am I doing wrong?

Thanks once again!

sed '/^10002,11/{N;s/\n10004,9/\
10003,9&/;}' filename

There is an escaped new line after the pattern "\n10004,9".

awk 'x&&/^10004,9/{$0=y RS$0}
{x=(/^10002,11/)?1:0}1' y="10003,9" filename

Use nawk or /usr/xpg4/bin/awk on Solaris.

Hi Guy,

You can use awk to realize it.
in:

10002,9:12/123456789
10002,10:1
10002,11:1
10004,9:12/123456789
10004,10:1 
10002,9:12/123456789
10002,10:2
10002,11:2
10004,9:12/123456789
10004,10:2

out:

10002,9:12/123456789
10002,10:1
10002,11:1
10003,9
10004,9:12/123456789
10004,10:1
10002,9:12/123456789
10002,10:2
10002,11:2
10003,9
10004,9:12/123456789
10004,10:2

code:

awk'
BEGIN { FS=":"}
{
if ($1=="10002,11")
var=$0
else if ($1=="10004,9")
{
	var=sprintf("%s\n10003,9\n%s",var,$0)
	print var
}
else
print
}' a

How silly!

thanks for the correct solution!