Sometimes, we want to find a specific process running on our system. The most common solution for this is to use grep. grep stands for "global regular expression print" and it is a useful command in Linux.
In fact, 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.
Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Linux C=system commands queries.
In this context, we shall look into how to exclude in grep.
To display lines that don't match the search pattern, let's use the -v option.
Now We have a file named fn.txt. which contains the following contents:
limit
ab cd
...
abcd
When you run the below command:
$ grep -v function fn.txt
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, we want to exclude the line that contains string ab cd:
$ grep -v 'ab cd' fn.txt
You will see the below output:
limit
limit of function
...
abcd
If you want to specify multiple strings at once, let's use the -e option.
For example, We want to exclude limit and abcd string:
$ grep -v -e limit -e abcd fn.txt
You will see an output such as this:
ab cd
...
If you only want to exclude words that show at the beginning of a line. For example, we want to exclude the word function that appears at the beginning of a line:
$ grep -v '^function' fn.txt
The output will look like this:
limit
limit of function
ab cd
..
abcd
Because the word function appears at the ending of the line, it won't be excluded.
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
The output will look like:
/home/kong/.bashrc:# don't put duplicate lines or lines starting with space in the history
/home/kong/.profile:# the files are located in the bash-doc package.
From the 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, we want to exclude files that contain the string Linux inside the ubuntu and food directory:
$ grep -r --exclude-dir={ubtuntu,food} linux /
From the output, the red part is filtered out.
This article covers how to exclude in grep. In fact, grep is a powerful command-line tool that is used to search one or more input files for lines that match a regular expression and writes each matching line to standard output.