Reputation: 783
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
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
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