7

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

3 Answers 3

14

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.
10
  • 1
    How to pass variable instead of ST here ?
    – rajagopalx
    Jan 10, 2017 at 16:54
  • @RajagopalSubramanian a shell variable? If so, you can use -v parameter and pass in variables, but if it's an environment variable it's even easier because you can use ENVIRON["TERM"] for your variable in the awk expression itself.
    – Dan
    Jan 10, 2017 at 16:55
  • yes. A shell variable
    – rajagopalx
    Jan 10, 2017 at 16:56
  • @RajagopalSubramanian yes, you should find it if you search. I also updated my comment above. However, this was not part of the question so it is not reflected in my answer.
    – Dan
    Jan 10, 2017 at 17:00
  • very sorry guys.
    – rajagopalx
    Jan 10, 2017 at 17:02
5

Get ST in column 2 (-E and {1} can be omitted here):

grep -E '^([^,]*,){1}ST[^,]*' file

Output:

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

Get ST in column 6:

grep -E '^([^,]*,){5}ST[^,]*' file | column -s, -t

Output:

6  N1  N101  2  3  ST
0

By using awk we can select required column,

column -s, -t < myfile.txt | awk '$2 == "ST"'

If shell variable used,

seg="ST"
column -s, -t < $ST_FILE | awk -v var="$seg" '($2 == var)'

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.