Tuesday, June 29, 2010

Exact match with UNIX grep and awk


Input file:

$ cat file.txt
1 172.17.4.1
2 172.17.4.5
3 172.17.4.8
4 172.27.4.19
5 172.24.4.12

Now:

$ grep '172.17.4.1' file.txt
1 172.17.4.1
4 172.17.4.19
5 172.17.4.12

Are you trying to grep exact '172.17.4.1' ?

From grep man pages:

-w, --word-regexp

Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.


$ grep -w '172.17.4.1' file.txt
1 172.17.4.1

Another alternative:

$ grep '\<172.17.4.1\>' file.txt
1 172.17.4.1

Normal awk match:

$ awk '$2 ~ /172.17.4.1/ {print $1}' file.txt
1
4
5

To make it exact match,
From gawk man pages

\y
matches the empty string at either the beginning or the end of a word.

So,

$ awk '$2 ~ /\y172.17.4.1\y/ {print $1}' file.txt
1

For exact match in awk, you can use this though

$ awk '$2=="172.17.4.1" {print $1}' file.txt

Related posts :

- Highlight match with color in UNIX grep command
- Print only matched string not line using UNIX grep
- Grep and print control characters in file - UNIX

5 comments:

Unknown said...

Thanks for the awk $2=='' trick, really handy!!!

Unknown said...

Thanks
it works !!

caezsar said...

Pfff....searched for an hour on a exact string match with grep command and found it here with grep -w
Thanks a lot man!

Unknown said...

@caezsar, thanks !

Unknown said...

Be aware that the expression:
grep -w "172.42"
will match 172x42 as also 172.42 since the . means to match any char.

So either we turn off the metacharacters in the grep regexp (172\.42)
or better yet use the -F option, like as
grep -Fw "172.42"
which instructs grep to treat the regexps as fixed strings.

HTH

© Jadu Saikia www.UNIXCL.com