I need to search multiple patterns on the third column of a file, and then print the whole line.

I am using this one below but how do I get it to print the whole line where there is a match?

awk '{print $3}' file | egrep -w "S|M|D"
  • please click edit and add few lines of input and expected output - some line should match and others shouldn't... this will help to add clarity to question as well as act as test data for those who wish to answer your question
    – Sundeep
    Jan 7, 2019 at 9:23

3 Answers 3


I think your requirement just needs awk and not a combination with grep. If you are looking to print the whole line where the third column matches any of those letters, you need to do

awk '$3 ~ /^(S|M|D)$/' file
  • 2
    since it is single character, you can also use [SMD]
    – Sundeep
    Jan 7, 2019 at 9:28
  • is this going to search for the exact match? like grep -w does?
    – hayabusa99
    Jan 7, 2019 at 9:33

To extract the lines whose 3rd whitespace-delimited field is exactly S, M or D, use one of

awk '$3 ~ /^[SMD]$/' file

or, using string matching rather than regular expression matching,

awk '$3 == "S" || $3 == "M" || $3 == "D"' file

A condition without a corresponding block will act as if its block simply was { print }.

awk '$3 ~ /^S/||/^M/||/^D/{print $0}' filename
  • The way this parses out will match column 3 starting with an S, or column 1 starting with an M or D -- it misses column 3 M/D and it incorrectly includes the column 1 matches.
    – Jeff Schaller
    Jan 9, 2019 at 19:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .