2

I'm having trouble trying to match an exact string with awk.

My intent is to search a csv for a match and get the line number of that match. So if I search for "1.1.1.2" in the below file I want it to return "1"

CSV

[apache@JBLAMPS001 tmp]$ cat test.csv
node2,1.1.1.2
node20,1.1.1.20
node21,1.1.1.21
node22,1.1.1.22
node102,1.1.1.102
node202,1.1.1.202

Things I've tried

[apache@JBLAMPS001 tmp]$ awk '/'1.1.1.2'/ {print NR}' test.csv
1
2
3
4
5
6

[apache@JBLAMPS001 tmp]$ awk '/\y'1.1.1.2'\y/ {print NR}' test.csv
1
5

[apache@JBLAMPS001 tmp]$ awk '"^1.1.1.2$" {print NR}' test.csv
1
2
3
4
5
6

Does anyone know how I can structure this? Thanks.

2

If you want to use Regex, you need to use proper modifiers and anchors to get only the desired match(es). In your case, the Regex pattern 1.1.1.2 (. means any single character BTW) will match all lines, hence the result. The last one is awk '"^1.1.1.2$" {print NR}' is not how you put a Regex pattern in awk -- you need to use either // or $<field> ~ <pattern>.


Here is how you can get your desired result:

  • Regex way: escape all .s to treat them literally, add $ to match end:

    awk '/1\.1\.1\.2$/ {print NR}' test.csv
    
  • String manipulation: printing the record number if the , followed by any horizontal whitespace separated last field is 1.1.1.2:

    awk -F ',[[:blank:]]*' '$NF == "1.1.1.2" {print NR}' test.csv 
    
  • 2
    @Jesse_b Pass the variable to awk: awk -F ',[[:blank:]]*' -v ipaddr="1.1.1.2" '$NF == ipaddr {print NR}' test.csv – heemayl Jul 5 '17 at 4:04
  • 1
    @Jesse_b Yes, i know. What i meant is: awk -F ',[[:blank:]]*' -v ipaddr="$ipaddr" '$NF == ipaddr {print NR}' test.csv – heemayl Jul 5 '17 at 4:07
0
ip=1.1.1.2; sed -ne "/,${ip//./\\.}\$/=" yourIPfile

Where we are escaping the dots . and give that to the sed command = which will display the matching line number.

0

You can always try good old grep:

grep -wFn 1.1.1.2 yourIPfile

or

ip=1.1.1.2 ; grep -wFn $ip yourIPfile

In both cases, output is

1:node2,1.1.1.2

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.