4

For Example: I have file like following:

AA ABC-AA-AA
AAA ABC-AA
ABC.AA ABC
AA ABC.A AA

If I use grep -w "ABC" file1, I am getting all the lines.

But I should only get 3rd line: ABC.AA ABC

It is taking . and - as word separators. But I need only space as word separator.

8

From (GNU) grep(1) man page:

-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.

Thus you'll need to explicitly request the spaces (or line beginnings and/or ends) to be there:

grep -E '(^| )ABC( |$)' file1

If you also want to include other white-space characters, replace the spaces above with a larger set, e.g. [[:space:]] (again see the grep(1) man page).

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.