Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

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.

like image 982
GB Hariharan Avatar asked Dec 05 '13 10:12

GB Hariharan


People also ask

How do you grep multiple lines after a match?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.

How do you grep for lines that don't match?

To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters). By default, grep is case-sensitive.

How do you grep after match?

To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.


1 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)

like image 181
Oliver Matthews Avatar answered Nov 24 '22 21:11

Oliver Matthews