Grep – How to Use Grep on Column

columnsgrep

I want to apply grep on particular column in column command.

myfile.txt

3,ST,ST01,3,3,856
3,ST,ST02,4,9,0234
6,N1,N101,2,3,ST
6,N1,N102,1,60,Comcast
6,N1,N103,1,2,92

My Command:

column -s, -t < myfile.txt | grep -w "ST"

Here I want to only grep the pattern ST in 2nd column. How to do this ?

Expected Result:

3       ST            ST01              3            3            856
3       ST            ST02              4            9            0234

Best Answer

Without doing some fancy RegEx where you count commas, you're better off using awk for this problem.

awk -F, '$2=="ST"'
  • The -F, parameter specifies the delimiter, which is set to a comma for your data.
  • $2 refers to the second column, which is what you want to match on.
  • "ST" is the value you want to match.
Related Question