Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep without string

Tags:

string

grep

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?

like image 565
Mika H. Avatar asked Nov 06 '12 21:11

Mika H.


People also ask

How do you grep without a string?

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.

How do I grep without output?

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.

How can I grep without name?

“-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.”

How do I exclude multiple words in grep?

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.


2 Answers

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.

like image 85
sampson-chen Avatar answered Sep 23 '22 06:09

sampson-chen


This might do it.

fgrep "abc" file | grep -v "def" 
like image 31
alex Avatar answered Sep 22 '22 06:09

alex