1

I have a file like this:

apple 1
apple 2
mango 3
apple 2
mango 4
mango 5
apple 3
apple 4
cherry 6
cherry 7
cherry 8
apple 5
cherry 9

and I want to use awk or sed in a single line to remove the line that matches the consecutive line with the pattern apple retaining the second line. I also want to retain rest of the lines that do not match the pattern and get the output like this:

apple 2
mango 3
apple 2
mango 4
mango 5
apple 4
cherry 6
cherry 7
cherry 8
apple 5
cherry 9
2

A bit more optimize awk script that yours:

awk '$1=="apple"{l=$0;next}l{print l; l=""}1' file 

That relies on storing into the variable l the line that match the apple pattern. The stored line is printing only when the pattern is not found.

  • This worked perfectly and better than my solution. Thank you. – clouusau Aug 30 at 19:00
  • How can this be improved if I want to eliminate every line with apple that has mango in the next line. – clouusau Aug 30 at 21:19
1

I got the answer after some trial and error:

awk '{a=$1;b=$2;row1=NR;getline;row2=NR;c=$1;d=$2;if(row1==row2 || (a=="apple" && c=="apple")) {print c " " d;} else {print a " " b;print c " " d;}}' FILE

This gives the output:

apple 2
mango 3
apple 2
mango 4
mango 5
apple 4
cherry 6
cherry 7
cherry 8
apple 5
cherry 9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.