Reputation: 2953
I have a file that contains strings, and I would like to check if a string exists in that file as a separate word. example:
string = rambox
file that contains "rambox":
initrd=yahya/rambox/initramfs11.cpio.gz rambox ramdisk_size=5242880 ...
"grep" command will tell that "rambox" exists
file not containing "rambox"
initrd=yahya/rambox/initramfs11.cpio.gz ramdisk_size=5242880 ...
"grep" command will tell that "rambox" exists coz it exists as a substring of the path "initrd=yahya/rambox/initramfs11.cpio.gz" and this is not correct. I want to obtain that "rambox" doesn't exist in the second example. Is there a way ?
Upvotes: 0
Views: 137
Reputation: 603
even the answer from Maroun Maroun sims right I would change space by this regexp [[:space:]] which will cover all free space like for example tab
input file
# cat testfile
rambox test test
testrambox test test
test test rambox with tab
test test rambox
test testrambox
#
output:
# grep -P '(^|[[:space:]])rambox($|[[:space:]])' testfile
rambox test test
test test rambox with tab
test test rambox
#
Upvotes: 1
Reputation: 39374
Sounds like you want "rambox" to be surrounded by any amount of white-space or at the beginning or ending of the line. \b
and other word boundary solutions (eg, grep -w
) won't work here, because /
counts as a non-word.
You could write your own interpretation of "word boundary", but in this simple case it's not really worth it.
For this case, I'd probably just manually handle the beginning of line and end of line scenarios:
$ cat -vet junk
rambox$
rambox$
rambox $
rambox$
foo rambox bar$
foo rambox bar$
/rambox/$
ramboxfoo$
ramboxfoo $
foorambox$
foorambox $
$ egrep '(^\s*rambox\s+|\s+rambox\s+|\s+rambox\s*$)' junk
rambox
rambox
rambox
foo rambox bar
foo rambox bar
Upvotes: 1
Reputation: 95958
You can use grep
with the -P
flag:
grep -P '^rambox | rambox$| rambox '
Or even better:
grep -P '(^| )rambox($| )'
^
matches beginning of line$
matches end of line|
is OR regex-P, --perl-regexp
PATTERN is a Perl regular expressionUpvotes: 3