Like grep, only if pattern1 and pattern2 match on consecutive lines

I have a file as shown below:

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

Question. I want grep cityand foodfor which the “food” is “bad”.

For example - for the above question, I need the grep command to get an answer, as shown below.

city-india
bad food

Please help me, how will I get pattern 1 and pattern 2 grepped only if both run successfully in parallel.

i means that both patterns must match and it should be grep in the next line.

+4
source share
6 answers

You can do this using pipes - grep -A1 city <filename> | grep -B1 "bad food"or cat filename | grep -A1 city | grep -B1 "bad food"(or any other flow source for the channel)

+5
source

( ):

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

.

+1

bad food gnu awk (- RS)

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

awk:

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

, grep OR:

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

, , .

:

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

, .

0

, , "" ( ):

grep -x -e'city-.*' -e'good food' -e'bad food' -e'-' | tr \\n \| | sed -e's/|-|/\n/g' | grep -xe'[^|]\+|[^|]\+' | grep -e'|bad food$' | tr \| \\n

  • grep -x -e'city-.*' -e'good food' -e'bad food' -e'-': , " ", " " ( ), " " ( , ) -x grep , (, "" ),

  • tr \\n \|: ( , , , , ),

  • sed -e's/|-|/\n/g': |-| ( , , "" , , , , , "" , ),

  • grep -xe'[^|]\+|[^|]\+': , (, ),

  • grep -e'|bad food$': , |bad food,

  • tr \| \\n: ( , , ).

grep -x -e'city-.*' -e'good food' -e'bad food' -e'-':

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

tr \\n \|:

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

sed -e's/|-|/\n/g':

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

grep -xe'[^|]\+|[^|]\+': idem, " " " " , " " " ", , " " " ", ... ,

grep -e'|bad food$':

city-india|bad food

tr \| \\n:

city-india
bad food

""?

"", "", , "" , "", .. - .

, , :

  • -,

  • " " city-*,

  • " " - good food bad food,

  • , "city" "food".

( , , "" , , ).

, :

  • "" "",

  • "" "".

, , , sed awk, , , .

All in all, it's just a matter of taste.

0
source

All Articles