Skip to main content

Grep Command Examples of How to Search a File for a Pattern

The UNIX Grep command searches files for a user-specified text pattern. It returns a list of the matching words or shows each line of text that contains them. You can broaden the results by using wildcards. Grep also has the ability to count instances of a search phrase that appear in a file.

The syntax for this UNIX command includes three parameters, but only the text pattern is required:

grep [options] pattern [filename]
If it contains multiple words or special characters, be sure to place single quotation marks before and after the pattern. The UNIX shell does not interpret dollar signs, brackets, parentheses, pipes or asterisks in the same way as letters. For example, an asterisk is treated as a wildcard when you don't use quotes.

If you leave out the filename, UNIX will collect data from the standard input device. This is usually the keyboard.

(1) Basic search with no options
The following example shows what happens if you use grep to search for the word "unix" in a text file:

$ cat examplefile.txt
this is line 1 UNIX UNIX
this is line 2 unix
this is line 3 Unix Unix
this is line 4 hello

$ grep unix examplefile.txt
this is line 2 unix
By default, it displays the only line that contains "unix" in lowercase letters.


(2) Ignore upper and lower case distinction
One of the grep options allows you to search for words in a case-insensitive manner:

$ grep -i unix examplefile.txt
this is line 1 UNIX UNIX
this is line 2 unix
this is line 3 Unix Unix
All lines containing the word unix, regardless of if it's lowercase, uppercase or a mix of both, are returned.


(3) Add line numbers to search results
The "-n" option adds line numbers to the output:

$ grep -n unix examplefile.txt
2:this is line 2 unix
This makes it easier to locate the pattern in a large file that doesn't have its own line numbers.


(4) Display how many lines contain the search pattern
Another option instructs grep to count the number of times a pattern appears. It will not show any lines or words when you use the "-c" option.

$ grep -c unix examplefile.txt
1

$ grep -ci unix examplefile.txt
3
The second example above shows that you can always add "-i" to perform case-insensitive searches.


(5) Quiet mode search
Adding the -q option prevents grep from writing anything to standard output. This is useful when grep is embedded within a shell script and you want to check if a pattern exists in one or more files but do not want to generate any output during processing. The result (return value) of the search can then be checked by the shell script to determine what logic should be followed.

$ grep -q unix examplefile.txt
$ echo $?
0

$ grep -q bob examplefile.txt
$ echo $?
1
Note: It should be obvious, but if it's not 0 indicates true, meaning a match was found. A result of 1 indicates no match was found. If you are not familiar with command return values, or return values in general, 0 typically always means true and a non-zero number (it does not have to be 1) means false.


(6) Show only the part of line matching pattern (Linux ONLY)
The grep command in UNIX doesn't support the "-o" option, but you may use it under Linux. It is desirable when you only want to display the matching patterns:

$ grep -o unix examplefile.txt
unix

$ grep -oi unix examplefile.txt
UNIX
UNIX
unix
Unix
Unix
Nothing too interesting (or exciting) here.


(7) Show lines from file that DO NOT contain the search pattern
You can search for lines that don't contain a pattern by adding the "-v" option. It may be used on both UNIX and Linux systems, and as you will discover, is a VERY handy option to know.

$ grep -v unix examplefile.txt
this is line 1 UNIX UNIX
this is line 3 Unix Unix
this is line 4 hello

$ grep -vi unix examplefile.txt
this is line 4 hello

(8) Search file for multiple patterns or for patterns beginning with hyphen (-) (Linux ONLY)
You may use "-e" to find multiple words or a pattern that begins with a hyphen. The "-e" option is not accepted by grep in UNIX, but Linux will list every line that contains at least one of the words:

$ grep -e unix -e hello examplefile.txt
this is line 2 unix
this is line 4 hello

(9) Search multiple files for a pattern
Grep will search multiple files if you add a wildcard to the filename. It lists the name of a file before each line. A wildcard search may come in handy when you can't remember what file contains a certain data item. These UNIX grep command examples show how it works:

$ cat examplefile.txt
this is line 1 UNIX UNIX
this is line 2 unix
this is line 3 Unix Unix
this is line 4 hello

$ cat examplefile2.txt
this is line 1 hello
this is line 2 Unix
this is line 3 UNIX UNIX
this is line 4 unix unix

$ grep unix examplefile*
examplefile.txt:this is line 2 unix
examplefile2.txt:this is line 4 unix unix

$ grep -i unix examplefile*
examplefile.txt:this is line 1 UNIX UNIX
examplefile.txt:this is line 2 unix
examplefile.txt:this is line 3 Unix Unix
examplefile2.txt:this is line 2 Unix
examplefile2.txt:this is line 3 UNIX UNIX
examplefile2.txt:this is line 4 unix unix

(10) Recursive search (Linux ONLY)
The -r option can be used to recursively search all files under a directory. Although there are multiple methods for achieving the same results (like most things in UNIX and Linux), having an easy to remember option to use with the grep command simplifies the task for you.

$ find .
.
./examplefile.txt
./subdir1
./subdir1/examplefile2.txt
./subdir2
./subdir2/examplefile3.txt

$ grep -r unix .
./examplefile.txt:this is line 2 unix
./subdir1/examplefile2.txt:this is line 4 unix unix
./subdir2/examplefile3.txt:this is line 1 unix

Grep has a wide range of practical applications. You may use it to find specific pieces of information in large groups of text files. If you write computer programs, consider using it to generate a list of source code lines that contain a certain variable or function call. The UNIX grep command also proves helpful when you need to determine how many times you have used a particular word in a document.

11.Search in more than one file

If more than one file is supplied in argument list then grep searches for the pattern or string in all the files.

For example :
# grep "Linux" input.txt output.txt
input.txt:Welcome to Linux.
output.txt:I hope you enjoyed working on Linux.

12.grep to search for multiple words:
grep -r "drupal\|joomla\|wordpress"/home/work

13. Below command will print a list of files containing any word starting with "mod".
grep -lr "mod.*" .




14. find /home/work -type f | xargs grep -c check $1 | grep -v ":$0"
As for the grep flags ...

-c will return a filename followed by : and a number indicating how many times the search string appears in the given file.

-v will take the output from the first grep search, filter out the files with zero results, and print out just the files with non-zero results.


Comments

Popular posts from this blog

Files creation

In LINUX files can be created by using any of the three methods given below:        1.  Cat command (cat - CONCATENATION)        2. Touch command        3. Vi editor 1. cat command: cat stands for CONCATENATE. This is the basic command when we start learning LINUX/UNIX, as the name suggest it is used to create new file, concatenate files and display the content of the files on the standard output.     Different examples of cat command which will be useful for the beginners. 1. Creating new file 2. View the contents of the file 3. View the contents of  multiple files 4. Display the output of a file using page wise 5. cat command without filename arguments 6. Display the content of a file with line numbers 7. Copy the contents of a one file to another file 8. Appending the contents of one file to another file 9. Redirecting the output of multiple files into a single file. 10. Getting input using standard input operator 11. Storing the output of multiple files into

grep Word Count Command

How do I count words using grep command under Linux / Unix like operating systems? You can pass the -c option to grep command to suppress normal output and display a count of matching lines for each input file. The syntax is follows: grep -c "string" file In this example, search for a word called ‘var’ and display a count of matching lines: grep -c 'var' /etc/passwd You can pass the -v option to count non-matching lines: grep -v 'var' /etc/passwd However, this will not count words. To count exact matched words, enter: grep -o -w 'word' /path/to/file/ | wc -w The grep -o command will only display matched words and the wc -c command will display the word counts.