Introduction
grep stands for “global regular expression print” and it is a useful command in Linux.
The grep command is used to filter out input files that match a regular expression then print to standard output. And it is also very important to exclude words and patterns or dictionaries and files.
Below is the guide on how to exclude in grep as we go through below.
Exclude words and patterns
To display lines that don’t match the search pattern, let’s use the -v option.
Now I have a file named fn.txt.that contains the following contents:
For example, I want to exclude the line that contains the word function:
$ grep -v function fn.txt
Output:
As you can see, the line that contains the word function is filtered out.
if the string that you wanna search contains space, you must use parentheses or quotes.
For example, I want to exclude the line that contains string ab cd:
$ grep -v 'ab cd' fn.txt
Output:
if you want to specify multiple strings at once, let’s use the -e option.
For example, I want to exclude limit and abcd string:
$ grep -v -e limit -e abcd fn.txt
Output:
If you only want to exclude words that show at the beginning of a line. For example, I want to exclude the word function that appears at the beginning of a line
$ grep -v '^function' fn.txt
Output:
Because the word function appears at the ending of the line, it won’ be excluded.
Exclude directories and files
To exclude a directory that you specified, use the –exclude-dir with -R or -r option. -R will follow all symbolic links. This is also the biggest difference between -r and -R options.
For example, I want to exclude files that contain the string cat inside the /home/ubuntu directory:
$ grep -R --exclude-dir=ubuntu cat /home
Output:
The red part is filtered out.
To exclude multiple directories at once, put directories in curly braces and separate by commas with no spaces.
For example, I want to exclude files that contain the string Linux inside the ubuntu and food directory:
$ grep -r --exclude-dir={ubtuntu,food} linux /
Output:
The red part is filtered out.
Conclusion
You’ve already gone through the details of how to exclude in grep.
Thanks for reading.