13 Practical Grep Command Examples In Linux / UNIX

13 Practical Grep Command Examples In Linux / UNIX

The grep is the best command line tool for searching text in files. It also used for the searching files containing specific files recursively. Grep has multiple command line options to make this tool great. Generally, all the system administrator must use these commands daily in there working. In this tutorial, you will know, How do I use grep command in Linux for searching text in files.

How to search text with grep:

Search for the text “manju” in /etc/passwd file. It will display all matching lines containing searched text as result.

$ grep "manju" /etc/passwd

Use can also use piped input to grep

$ cat /etc/passwd | grep "manju" 

Use grep without case sensitive search

Use -i option to tell grep to ignore case during search. It means it will search for manju, MANJU, maNJl etc.

$ grep -i "manju" /etc/passwd

Use grep to search multiple words

Use multiple strings to search in file with grep command with pipe separated

$ grep "manju|linuxmasterswiki|root" file

Use grep to search in multiple files

Grep can search in multiple files as well. Search “manju” in file1, file2 file3 etc.

$ grep "manju" file1 file2 file3 

Use grep to search in multiple files

Grep can search in multiple files as well. Search “manju” in file1, file2 file3 etc.

$ grep "manju" file1 file2 file3 

Search in all files in a directory

Using wildcard characters, you can search string in all files or files with specific extension in a directory

 
$ grep "manju" *            #Search in all files
$ grep "manju" *.txt        #Search in specific extension files

Count total lines the word matched

Use -c to print total number of lines the searched string matched in files.

$ grep -c "manju" file

Print matched content with line number

Use -n to print matched content with line number of matched content .

$ grep -n "manju" file

Match whole line only

Using -x prints content only matched whole lines

$ grep -x "manju" file

Invert search with grep

The -v option only select lines those non-matching with searched string.

$ grep -v "manju" /home/

Search recursively in multiple files

grep commands also allows to search in file hierarchy recursively. Use -r to search recursively with grep command.

$ grep -r "manju" /home/

Print matched content filename only

Using -l prints the matched filename only. its useful with recursively search where lots of search content shows.

$ grep -rl "manju" /home/

Grep in specific extenson file with recursive

Using –include=PATTERN to search for speicifc extension files only with recursive.

$ grep -R --include="*.php" "manju" /home/
 
Enjoyed this video?
13 Practical Grep Command Examples In Linux / UNIX
"No Thanks. Please Close This Box!"