Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep a whole whitespace-separated word in bash

Tags:

regex

grep

unix

awk

Say I have this data:

hi helo tmp#100000 bye
100000 hi bye
hi 100000 bye

And 100000 is in variable: $var I want to grep 100000 only as a whole word, desired output:

100000 hi bye
hi 100000 bye

I have tried everything that ever been answered in StuckOverflow and nothing seem to work: grep "\b$var\b", grep -E "[[:blank:]]$var[[:blank:]]" and many many more. I think the problem, might be in #. The solution needs to work for a case where the variable equal: hi.*bye as a Regex as well.

Please help

like image 742
jenny Avatar asked Jan 19 '26 00:01

jenny


1 Answers

Non-regex search using awk:

awk -v var="$var" '
{for (i=1; i<=NF; ++i) if ($i == var) {print; break}}' file
100000 hi bye
hi 100000 bye

Otherwise a shorter awk using custom FS:

awk -F "(^|[[:blank:]])$var([[:blank:]]|$)" 'NF > 1' file
like image 101
anubhava Avatar answered Jan 21 '26 20:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!