Search for 2 string in 2 lines with sed ?

Hi !
I want to search a string in all lines with sed. If that string is there, i want to look for an other string in the next line.If that string is there i want to put an other line under it.

eg:

aaa
bbb
ccc
ddd
cat bla.txt | sed -e '/aaa/a\' -e ' \!!!'

in the upper case, i would have following outputbacause i am looking for aaa:
aaa

!!!
bbb
ccc
ddd

how can i look for that aaa and check that the next line is bbb so i can have the following output:

aaa
bbb
!!!
ccc
ddd

Thanks for your help
Mfg Fugitivus

How about

sed -e '/aaa/ {N; /aaa\nbbb/ s/$/\n!!!/}' file

given your sed version allows for the "\n" replacement...

If your sed doesn't allow backslash escapes in the replacement text of a substitute command, try:

sed '/aaa/a\
!!!
' bla.txt

Note that there must be a newline immediately following the backslash. If you want to put this in a script and pass in the string to be searched for as the 1st operand and the name of the file to be searched as the 2nd operand, try:

#!/bin/ksh
sed "/$1/"'a\
!!!
' "$2"

so you could invoke:

myscript "aaa" bla.txt

to get the 1st output you wanted and:

myscript "bob" bla.txt

to get the 2nd output you wanted.

This example uses the Korn shell, but this will work with any shell that is based on Bourne shell syntax.

Thank you for your Help !

sed -e '/aaa/ {N; /aaa\nbbb/ s/$/\n!!!/}' file

is a realy good thing. is there a way to work with negations ?
like if i would look for an aaa and and print a bbb to the next line if bbb not exists in that line ?!?

Mfg Fugitivus

Try:

sed '/aaa/{N; /\nbbb/!s/\n/&bbb&/;}' file

Although that would not work for occurrences of aaa on the last line..

--
Also last line:

sed '/aaa/{$s/$/\
\bbb/; $!N; /\nbbb/!s/\n/&bbb&/;}' file

Only GNU sed works as a one-liner. The classic Unix sed needs a multi-liner:

sed '
  /aaa/ {
    N
    /bbb/ a\
!!!
  }
' bla.txt

Thanks thats exactly what i want to do !!!
I'll think i have to experimentate a little bit more to understand sed :slight_smile:
Realy nice tool !!!

Mfg Fugitivus