Reputation: 325
I want to grep lines contains all 3 different patterns, and output them with 2 previous lines and 1 next line.
This is the command I could grep without multiple line output. Now I want to add 3 additional line mentioned above. Can I put -A and -B together? Or do I have to use -C? Where should I put those options, all in three conditions or first or last?
grep -e Melon -e Banana -e Lemon *txt | grep Tomato | grep Milk
This is sample input
Egg Tomato
Salad Coffee
Melon Tomato Milk
Noodle Salmon
Banana Potato Milk
Salmon Rice
Expected output is
Egg Tomato
Salad Coffee
Melon Tomato Milk
Noodle Salmon
Upvotes: 1
Views: 979
Reputation: 8174
A large solution, you want: Two lines above and one line below of pattern: (Melon or Banana or Lemon) and Tomato and Milk
grep -A1 -B2 -E -e "(Tomato.*Milk|Milk.*Tomato).*(Melon|Banana|Lemon)" \
-e "(Melon|Banana|Lemon).*(Tomato.*Milk|Milk.*Tomato)" \
-e "Tomato.*(Melon|Banana|Lemon).*Milk" \
-e "Milk.*(Melon|Banana|Lemon).*Tomato" *txt
Only for fun
Another solution using awk
awk '
flag{print; flag=0}
/Melon|Banana|Lemon/ && /Milk/ && /Tomato/{
printf "%s\n%s\n%s\n",prev[0],prev[1],$0
flag=1; next
}
{prev[0]=prev[1]; prev[1]=$0}' *txt
Upvotes: 2