0

My file contains the following text

xyz.com       123  321
xyz.com.br    123  123
abcd.xyz.com  123  321

I want to grep the line which contains xyz.com alone. ie, the output should be the first line.

 xyz.com   123  321

Tried the following but no avail.

grep "^xyz.com$" file.txt
grep '^xyz.com$' file.txt
grep -w xyz.com file.txt
grep '^xyz.com$' file.txt
grep '^xyz\.com$' file.txt
grep -Fx xyz.com file.txt
grep -w 'xyz.com' file.txt
grep -w 'xyz\.com' file.txt
grep '\sxyz.com\s' file.txt
grep '\bxyz.com\b' file.txt
grep "\bxyz.com\b" file.txt
grep "\<xyz.com\>" file.txt
grep '\<xyz.com\>' file.txt
grep -w -l "xyz\.com" file.txt
grep -w "xyz\.com" file.txt
grep -wF "xyz\.com" file.txt
grep -w "xyz\.com$" file.txt
grep -w "xyz\.com\$" file.txt

Shell is bash. Thanks.

0
$ grep '^xyz\.com[[:space:]]' file.txt
xyz.com      123 321
$ grep -P '^xyz\.com\s' file.txt
xyz.com      123 321

The first uses the POSIXy way of matching whitespace, the second use the perly way, which means you need to specify with -P using perl regular expressions.

0

In your example the line does not contain xyz.com alone, it contains more columns with numbers. This is why '^xyz\.com$' did not work. Try:

grep '^xyz\.com\s' file.text

The added \s at the expression end, force a space character right after the searched string and allow other text after.

To include the case of a line with only the search string try:

grep '^xyz\.com\(\s.*\)\?$' file.txt

It will allow line end right after the string but require a space in any other case.

See regular-expressions.info for more information on regular expressions.

  • 1
    What grep are you using that uses perl syntax for whitespace by default? Just curious... – blm Oct 22 '15 at 6:45
  • 1
    @blm, GNU grep 2.16 on ubuntu 14.04 – amotzg Oct 22 '15 at 6:51
  • 1
    Thanks. I'm using gnu grep but it's an older version and perl syntax doesn't work without -P. Time to upgrade... – blm Oct 22 '15 at 6:53

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.