Reputation: 91
I have a csv with the below data
10.000.00.00,D3,1
10.001.00.00,C4,2
10.002.00.00,C5,2
10.000.88.99,B1,3
10.000.00.00,B2,3
10.000.00.00,C6,3
10.000.99.00,D1,3
tried below code
cat Data.csv | awk -F , '$3 == "3" { print }'
Need to get only the rows having last values as 3.
Please let me know how to do this
Upvotes: 1
Views: 1076
Reputation: 37454
Using awk to get only the rows having last values as 3:
$ awk -F, '$NF==3' file
10.000.88.99,B1,3
10.000.00.00,B2,3
10.000.00.00,C6,3
10.000.99.00,D1,3
Explained:
awk -F, ' # set the field separator to a comma
$NF==3 # NF is the last field, $NF last field value (see comments for more
' file #thanks @kvantour)
Upvotes: 6
Reputation: 1254
you can use built in awk variable for this.
in our case
'$NF' - NF is for the number of fields in the current record
awk -F, '{if($NF == 3) {print $0} }' Data.csv
10.000.88.99,B1,3
10.000.00.00,B2,3
10.000.00.00,C6,3
10.000.99.00,D1,3
You can learn more about built in varible at following link: Awk Built in Variables
Upvotes: 0
Reputation: 12448
Why do we need
awk
orsed
for this kind of operations in the first place??? Isn't it an overkill?OP is asking about extracting some lines meeting a specific condition from the file without even modifying their format...
grep
is THE perfect tool for this.
$ grep ',3$' Data.csv
10.000.88.99,B1,3
10.000.00.00,B2,3
10.000.00.00,C6,3
10.000.99.00,D1,3
Eventually grep -E ',3\r?$' Data.csv
if you have windows EOLs.
Also try avoiding as much as possible cat <FILE> | <COMMAND>
, instead pass directly the file to the command or redirect the stdin
from the file to the command (Command < file
).
Upvotes: 2
Reputation: 2491
You can try with sed :
sed '/,3$/!d' infile
If you can have \r at end of lines, try this way :
sed '/,3\r*$/!d' infile
Upvotes: 2