Ramesh.kbvr
Ramesh.kbvr

Reputation: 783

searching/extracting specific word not the complete line in unix

I would like to search a word in a file in Unix that should return only the word not the complete line.

For ex:

Sample.text:

Hello abc hi aeabcft 123abc OK

Expected output: abc aeabcft 123abc

If I search abc in file Sample.txt using grep, it will return complete line but I want the words that contains abc

Upvotes: 0

Views: 428

Answers (2)

anubhava
anubhava

Reputation: 784958

You can use grep -Eo with an enhanced regex to search all matching words

grep -Eo '\b[[:alnum:]]*abc[[:alnum:]]*\b' Sample.text
abc
aeabcft
123abc

As per man grep:

-o, --only-matching
Prints only the matching part of the lines.

Upvotes: 2

John B
John B

Reputation: 3646

If you need to also do other processing to the file that grep can't accomplish, you could use Awk for printing only the regex match on the line.

awk -v r="abc" '{m=match($0,r,a)}m{print a[0]}' file

Otherwise I'd just use anubhava's grep -o suggestion as it's shorter and clearer.

Upvotes: 1

Related Questions