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 ?
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 expression 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
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
#
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.