Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AWK to grab a row in a file by a certain column

Tags:

grep

bash

unix

awk

1|1001|399.00|123                                  
1|1001|29.99|234                                  
2|1002|98.00|345                                   
2|1002|29.98|456                                   
3|1003|399.00|567  
4|1004|234.56|456

How would I use awk to grab all the rows with '1002' in column 2?

If I wanted to grab all the rows with '2' in the first column, I could use grep ^2, but how do I search by different columns?

like image 576
Andrew Tsay Avatar asked Nov 20 '25 12:11

Andrew Tsay


1 Answers

The typical solution is:

awk '$2 == 1002' FS=\| input-file

you get a slightly different result with: $2 ~ 1002, which technically satisfies your query, but is probably not what you want. (It does a regex match, and so will match if the second column is "341002994").

like image 148
William Pursell Avatar answered Nov 23 '25 03:11

William Pursell