Sed - Pattern Searching

Hi,

Please take a look at the below eg. I would like to search for abc() pattern first and then search for (xyz) in the next line. If I can find the pattern, then I should delete the 3 lines.

I can only find the pattern and delete but I am unable to find two patterns and delete. Any response is appreciated.

Eg :

Existing file
------------
abc() {
when : (xyz)&a&b&a
}

abc(){
when : a&b&c
}

abc() {
when : a&b&c&(xyz)

Expected Result file
-------------------
abc(){
when : a&b&c
}

Thanks

use this code where you are searching for the patter without xyz

sed  -n '
/[ ]a&b&c$/ !{
h
}
/[ ]a&b&c$/ {
H
n
H
x
p
} ' input.txt

if you have Python on your system, an alternative

#!/usr/bin/env
data=open("file").read().split("\n\n")
for i in data:
    if not "(xyz)" in i:
        print i

output

# ./test.py
abc(){
when : a&b&c
}

Upon request from Mr. "rakeshawasthi" and to let the benefit to be spreaded between us I will explain the sed command I had wrote earlier:-

code:
sed -n '
/[ ]a&b&c$/ !{
h      # put the non-matching line in the hold buffer
}
/[ ]a&b&c$/ {
H            # found a line that matches
              # append it to the hold buffer

n             # the hold buffer contains 2 lines
	       # get the next line

H             # and add it to the hold buffer

x              # now print it back to the pattern space

p              # and print it.

} ' input.txt
$/="\n\n";
while(<DATA>){
	next if /abc.*\(xyz\).*/s;
	print;
}
__DATA__
abc() {
when : (xyz)&a&b&a
}

abc(){
when : a&b&c
}

abc() {
when : a&b&c&(xyz)
}

Thanks ahmad.diab!!! Thanks a lot.

The following sed command should do the job:

 sed '/abc()/{$!N;/\n.*(xyz)/{$!N;d;}}' filename  

When the pattern abc() is not found in the line, it is printed (standard sed behaviour) Otherwise, $!N;/\n.(xyz)/{$!N;d;} command is executed.
$!N appends next line of input file to the current pattern buffer if it is not the end of file already.
So after execution, we have something like previous_line/ncurrent_line in it. Then we search pattern '\n.
(xyz)' in the buffer, to emulate searching the line following the one with abc(). If the (xyz) pattern is found, $!N;d; command is executed, which appends the third line of input to the pattern buffer and then discards it.

Thanks a lot! It works big time :slight_smile:

-----Post Update-----

Thanks tkleczek!!! It works.

-----Post Update-----

Thanks tkleczek!!! It works.

-----Post Update-----

Ahmed,

Thanks for your response and detailed explanation. Somehow it does not work for me. Should I enter the "H n H x p" the different lines?

Thanks!

Yes you have to print it in a different line ...print the code litterally

or you can use {H;n;H;p }