I want to find all the lines in my text file containing the string "abc"
, but not containing the string "def"
. Can I use the grep
command to accomplish this task?
Searching for Lines Without a Certain String To search for all the lines of a file that do not contain a certain string, use the -v option to grep . The following example shows how to search through all the files in the current directory for lines that do not contain the letter e.
The quiet option ( -q ), causes grep to run silently and not generate any output. Instead, it runs the command and returns an exit status based on success or failure. The return status is 0 for success and nonzero for failure.
“-h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.”
Specify Multiple Patterns. The -e flag allows us to specify multiple patterns through repeated use. We can exclude various patterns using the -v flag and repetition of the -e flag: $ grep -ivw -e 'the' -e 'every' /tmp/baeldung-grep Time for some thrillin' heroics.
Either of the these will do:
grep -v "def" input_file | grep "abc"
or
grep "abc" input_file | grep -v "def"
The following will also preserve coloring if you only want to see the output on stdout:
grep --color=always "abc" input_file | grep -v "def"
The -v
option (stands for "invert match") tells grep
to ignore the lines with the specified pattern - in this case def
.
This might do it.
fgrep "abc" file | grep -v "def"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With