1

So the following grep matches 2 lines.

grep -w 1.2.3.4 testfile.csv 
1.2.3.4,Jim,Jonson,000000
1.2.3.4.5,George,Doe,FFFFF

How can I make it match exactly and only the specific word? In this example only 1.2.3.4.
Let's assume that whitespace in the beginning or next to the comma separator may appear and I would like this to be if possible cross platform grep.

  • should it match this -1.2.3.4-? – RomanPerekhrest Mar 27 '18 at 14:28
  • @RomanPerekhrest:No. No prefix or suffix – Jim Mar 27 '18 at 14:30
  • Here's gnu definition for word and non-word characters:-w Select only those lines containing matches that form whole words. The test is that the matching substring 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. As you can see it's quite different than your definition of non-word ... And btw, an unescaped dot matches any character so your grep -w 1.2.3.4 would also match 1a2b3c4 – don_crissti Mar 27 '18 at 14:38
  • @don_crissti:I want to demark it within the 2 , then – Jim Mar 27 '18 at 14:46
  • 1
    for given sample, awk -F, '$1=="1.2.3.4"' should work.. if not, please add some more samples – Sundeep Mar 27 '18 at 14:47
4

As noted by don_crissti in comments. The issue in your case is that the pattern trying to match 1.2.3.4 does not match the word conditions met for -w

Use the PCRE mode in your GNU grep if its supported. Using a positive lookahead

grep -P '^1\.2\.3\.4(?=,)' file

or as recommended by Sundeep without using PCRE just do

grep '^1\.2\.3\.4,' file

Also for more exact string match, awk is easier to do

awk -F, -v var="1.2.3.4" '$1==var' file
  • So with awk I avoid the issues with the regex and escaping . etc? – Jim Mar 27 '18 at 21:03
  • @Jim : Yes! That’s right. – Inian Mar 27 '18 at 21:21
  • I'll add a recommendation for grep '^ *1\.2\.3\.4 *,' testfile.csv as trailing whitespace is apparently allowed. – Jeff Schaller Mar 28 '18 at 0:59

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.