Home > Net >  How would I use grep to get only the Hondas?
How would I use grep to get only the Hondas?

Time:09-24

I used grep -A 4 L337 vehicles | grep -C 2 Blue | grep -B 4 6 to get these outputs but now I also need to filter it so it returns the outputs with the make Honda as well.

License Plate L337QE9
Make: Honda
Color: Blue
Owner: Erika Owens
Height: 6'5"
--
License Plate L337GB9
Make: Toyota
Color: Blue
Owner: Matt Waite
Height: 6'1"
--
License Plate L337OI9
Make: Jaguar
Color: Blue
Owner: Brian Boyer
Height: 6'6"
--
License Plate L337X19
Make: Fiat
Color: Blue
Owner: Al Shaw
Height: 6'5"
--
License Plate L3373U9
Make: Ford
Color: Blue
Owner: Miranda Mulligan
Height: 6'6"
--
--
--
License Plate L337369
--
License Plate L337DV9
Make: Honda
Color: Blue
Owner: Joe Germuska
Height: 6'2"
--
License Plate L3375A9
Make: Honda
Color: Blue
Owner: Jeremy Bowers
Height: 6'1"
--
License Plate L337WR9
Make: Honda
Color: Blue
Owner: Jacqui Maher
Height: 6'2"

CodePudding user response:

I'd grep by Make: Honda:

cat myfiles.txt | grep 'Make: Honda'

CodePudding user response:

You can probably get away with awk '/Honda/' RS=-

It would almost certainly be better to replace your prior grep pipeline with a single awk. Perhaps just

awk '/Honda/ && /L337/ && /Blue/' RS=- ORS=-- vehicles

Some versions of awk allow RS to be more than one character, so you might like RS=--, but the results are unspecified and it's not really necessary in this case.

CodePudding user response:

For the search append this to the existing pipeline:

| grep -A 3 -B 1 "Make: Honda"

Also, in your preliminary code replace this:

 | grep -B 4 6

with this:

 | grep -B 4 "^Height: 6'"

Otherwise, grep will obediently return License Plates with "6" too.

For similar reasons it's safest to use field names for every grep.

The total code would look like this:

grep -A 4 "^License Plate L337" vehicles | 
grep -C 2 "^Color: Blue" |
grep -B 4 "^Height: 6'" |
grep -A 3 -B 1 "^Make: Honda"
  • Related