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.

    Have you actually tried `grep -w`? (That option is exactly for that purpose, and it works for me.) - Note: option `-x` matches the whole line.

    *"I want to match exactly `deiauk`* / *"I only need this: `deiauk 1611516 afsdf 765`"* - which do you need?

  • Janis

    Janis Correct answer

    5 years ago

    Try one of:

    grep -w "deiauk" textfile
    grep "\<deiauk\>" textfile

    If you have a dash (**-**) at the end of the string this script will bring it as a result, which was not expected.

    Correct @Evert : Words include only alpha chars, digits and underscores, so if you have abbreviations or other items hyphenated, this does not work.

    @Cyrus I learnt the second one while using vi/vim `*` command on words.

    It does not work for any special character it have for example `org.apache.avro avro` greped with `org.apache.avro avro+mapred` (tried with *)

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM