0

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"
1
  • 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 Commented Jan 7, 2019 at 9:23

3 Answers 3

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
  • 2
    since it is single character, you can also use [SMD] Commented Jan 7, 2019 at 9:28
  • is this going to search for the exact match? like grep -w does? Commented Jan 7, 2019 at 9:33
1

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 }.

0
awk '$3 ~ /^S/||/^M/||/^D/{print $0}' filename
1
  • 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. Commented Jan 9, 2019 at 19:52

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.