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

2
  • 1
    Possible duplicate of grep with logic operators Oct 20 '19 at 0:30
  • ... although what I suspect you want to do is more like awk '$3=="ONT" && $5=="MONDAY"' i.e. match specific strings in specific columns Oct 20 '19 at 0:32
0

Could be:

grep "ONT.*MONDAY" file
3
  • 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 1: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. Oct 20 '19 at 1: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 1: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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.