3

I have this file

a deiauk Biking US 200 G
b kespaul 202 A
c deiauk NY 222 5 Z

And I want to match the exact string 200 using awk. So my result should be

a deiauk Biking US 200 G

Here's my code

awk -F ' ' '{if($(NF-1) ~ /200/){a[$1]++}}END{for (var in a){print a[var] " " var " " $(NF-1)}}' file.txt

But after that I got all lines.

lcd047
  • 7,238
user3334375
  • 1,795
  • Why do you expect your awk code to print a single line? Did you even bother to understand what this is supposed to do? – lcd047 Jun 02 '15 at 08:38
  • 1
    Your awk will print i) the number of times you have seen this 1st field where the penultimate field is 200; ii) the 1st field and iii) the penultimate field. Why would you expect it to print the whole line? What output are you actually getting? – terdon Jun 02 '15 at 09:49

3 Answers3

3

Since you want an exact match, why not use ==?

$ cat >file
a deiauk Biking US 200 G
b kespaul 202 A
c deiauk NY 222 5 Z
a auie auie 200 B
b nrst nrst 200 C

$ awk '$(NF-1)==200{a[$1]++}END{for (v in a){print  v,a[v]}}' file
a 2
b 1

You could also restrain your match with /^200$/:

$ awk '$(NF-1)~/^200$/{a[$1]++}END{for (v in a){print  v,a[v]}}' file
a 2
b 1

Edit:

I tried your command, and it should work. Are you sure of your -F ' '?

fredtantini
  • 4,233
3

With awk, just:

awk '$0~/ 200 /' file

Or sed (\s matches any whitespace):

sed -n '/\s200\s/p' file

A grep solution (-P for perl regex):

grep -P '\s200\s' file

If it has to be pure bash:

while read a; do [[ $a =~ " 200 " ]] && echo $a; done <file

If you're not sure if there are spaces, tabs, whatever ([[:space:]] is like \s, in the sed and grep solutions above):

while read a; do [[ $a =~ [[:space:]]200[[:space:]] ]] && echo $a; done <file
chaos
  • 48,171
0

I think this will help. This will print only the line containing pattern. In your case pattern is 200

grep '200' file-name