How to grep only if pattern1 and pattern2 matches in consecutive lines

Viewed 9383

I have a file like below:

city-italy
good food
bad climate
-
city-india
bad food
normal climate
-
city-brussel
normal dressing
stylish cookings
good food
-

Question - I want to grep city and food, for which "food" is "bad".

For example - for the above question, i need a grep command to get a answer like below

city-india
bad food

Please help me like, how i will get pattern 1 and pattern 2 grepped only if both succeeds parallely.

i mean both pattern should match and it should grep in the following line.

6 Answers

You can do it with pipes - grep -A1 city <filename> | grep -B1 "bad food" or cat filename | grep -A1 city | grep -B1 "bad food" (or any other stream source for the pipe)

If the city name is guaranteed to come before the food quality (any other info in between is allowed):

sed -n -e '/^city/h' -e '/bad food/{x;G;p}' input

Which keeps the name of each city in the hold buffer and prints the last city name when matches bad food.

If the order is ensured, you can use directly the command grep with OR:

grep -e "city" -e "food" FILE_INPUT

Then hopefully the city will follow by its food feature at following.

The result looks like:

city-italy
good food
city-india
bad food
city-brussel
good food

You can change your pattern to get a more filtered result.

To get city with bad food using gnu awk (due to RS)

awk '/bad food/ {print RS $1}' RS="city" file
city-india

another awk line:

kent$  awk 'BEGIN{FS=OFS="\n";RS="-"FS}/bad food/{print $1,$2}' file
city-india
bad food
Related