Match exact string using grep

I have a text file:

deiauk 1611516 afsdf 765
minkra 18415151 asdsf 4152
linkra sfsfdsfs sdfss 4555
deiauk1 sdfsfdsfs 1561 51
deiauk2 115151 5454 4
deiauk 1611516 afsdf ddfgfgd
luktol1 4545 4 9
luktol 1

and I want to match exactly deiauk. When I do this:

grep "deiauk" file.txt

I get this result:

deiauk 1611516 afsdf 765
deiauk1 sdfsfdsfs 1561 51
deiauk2 115151 5454 4

but I only need this:

deiauk 1611516 afsdf 765
deiauk 1611516 afsdf ddfgfgd

I know there’s a -w option, but then my string has to mach whole line.

Asked By: user3334375

||

Try this with GNU grep and mark word boundaries with b:

grep "bdeiaukb" file

Output:

deiauk 1611516 afsdf 765

See: http://www.regular-expressions.info/wordboundaries.html

Answered By: Cyrus

Try one of:

grep -w "deiauk" textfile

grep "<deiauk>" textfile
Answered By: Janis

If your grep supports -P (PCRE), you can do:

$ grep -P '(^|s)Kdeiauk(?=s|$)' file.txt 
deiauk 1611516 afsdf 765
deiauk 1611516 afsdf ddfgfgd
Answered By: heemayl

Depending on your real data, you could look for the word followed by a space:

grep 'deiauk ' file.txt 

If you know it has to be at the start of the line, check for it:

grep '^deiauk ' file.txt 
Answered By: Volker Siegel

I found -x worked for me.

Example

$ grep -inx -d skip 'favicon.ico' *
test.txt:1:favicon.ico

Grep Manual

-x, --line-regexp
              Select  only  those  matches  that  exactly  match the whole line.  For a regular expression pattern, this is like
              parenthesizing the pattern and then surrounding it with ^ and $.
Answered By: Tony Barganski
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.