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.txtfile that contain words with a characterbnot 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?
Advertisement
Answer
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]'meansb followed by any symbol that is not e-iis to ignore case, with this option lines containingBorbthat are not directly followed byeorEwill be accepted
The second solution calls grep twice:
- the first time you look for patterns that contains b only to select those lines
- the resulting lines are filtered by the second grep using
-vto reject lines containingbe - both grep are ignoring the case by using
-i if
bmust absolutely be followed by another character then useb.(regex meaningbfollowed by any other char) otherwise if you want to also accept lines wherebis not followed by any other character at all you can just usebin the first grep call instead ofb..grep -ie 'b' input_file.txt | grep -vi 'be'
input:
BEBE bebe toto abc bobo
result:
abc bobo