0

I'm looking to use grep(or egrep) to find two words that are on the same line. ONT and MONDAY

Flight#   Airline  Depart  Arrive  Day
------------------------------------------
93104      TEAM     ONT     LAX   MONDAY
62876       GE      NYC     ONT  THURSDAY
30118      LOGI     ONT     PHX   FRIDAY
12033       F       LAX     PHX   MONDAY
40990      ACTI     PHX     ONT   MONDAY
92377       EA      ONT     PHX   SUNDAY

I've tried various commands but every line that has MONDAY or ONT are returned instead of line with flight #93104

Freddy
  • 25,565

2 Answers2

0

Could be:

grep "ONT.*MONDAY" file
  • Given the data where the DOW is after the airport, this works; however, it wouldn't address the general question of "find two words that are on the same line" (where they could be in either order). – Jeff Schaller Oct 20 '19 at 01:35
  • @JeffSchaller That's true, but if they could be in either order then the awk solution doesn't address the heneral question either because those strings might not be in those respective columns. – Nasir Riley Oct 20 '19 at 01:42
  • 2
    Use two greps, piping the output of the first one into the second: grep ONT file | grep MONDAY. Order does not matter. – NickD Oct 20 '19 at 01:43
0

If you know that the ONT word is to be found in the 3rd column, and the MONDAY word in the 5th:

$ awk '$3 == "ONT" && $5 == "MONDAY"' file
93104      TEAM     ONT     LAX   MONDAY

This relies on the values in the columns to not have embedded whitespaces. The awk command above tests the values of columns 3 and 5 against the wanted words as strings and will output any line that passes the test.

To match ONT in either the 3rd or 4th column, and MONDAY in the 5th:

$ awk '($3 == "ONT" || $4 == "ONT") && $5 == "MONDAY"' file
93104      TEAM     ONT     LAX   MONDAY
40990      ACTI     PHX     ONT   MONDAY

If you used grep, you would not be certain that the two words matched complete words or in the correct columns (unless you made the regular expression overly complicated).

Kusalananda
  • 333,661