I'm working on my assignment and I've been stuck on this question, and I've tried looking for a solution online and my textbook.
The question is:
List all the lines in the
f3.txt
file that contain words with a characterb
not followed by a charactere
.
I'm aware you can do grep -i 'b'
to find the lines that contain the letter b
, but how can I make it so that it only shows the lines that contain b
but not followed by the character e
?
This will find a "b" that is not followed by "e":
$ echo "one be
two
bring
brought" | egrep 'b[^e]'
Or if perl is available but egrep is not:
$ echo "one be
two
bring
brought" | perl -ne 'print if /b[^e]/;'
And if you want to find lines with "b" not followed by "e" but no words that contain "be" (using the \\w perl metacharacter to catch another character after the b), and avoiding any words that end with b:
$ echo "lab
bribe
two
bring
brought" | perl -ne 'print if /b\w/ && ! /be/'
So the final call would:
$ perl -ne 'print if /b\w/ && ! /be/' f3.txt
Exluding "edge" words that may exist and break the exercise, like lab
, bribe
and bob
:
$ a="one
two
lab
bake
bob
aberon
bee
bell
bribe
bright
eee"
$ echo "$a" |grep -v 'be' |grep 'b.'
bake
bob
bright
You can go for the following two solutions:
grep -ie 'b[^e]' input_file.txt
or
grep -ie 'b.' input_file.txt | grep -vi 'be'
The first one does use regex:
'b[^e]'
means b followed by any symbol that is not e
-i
is to ignore case, with this option lines containing B
or b
that are not directly followed by e
or E
will be accepted The second solution calls grep twice:
-v
to reject lines containing be
-i
if b
must absolutely be followed by another character then use b.
(regex meaning b
followed by any other char) otherwise if you want to also accept lines where b
is not followed by any other character at all you can just use b
in the first grep call instead of b.
.
grep -ie 'b' input_file.txt | grep -vi 'be'
input:
BEBE
bebe
toto
abc
bobo
result:
abc
bobo
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.