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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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. $2refers to the second column, which is what you want to match on."ST"is the value you want to match.
Method 2
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
Method 3
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)'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0