Friday, 2 August 2019

Useful Examples of Linux grep Command

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.

Search Text in A File

You are searching if any fatal error reported in a log file. You can search the text “FATAL” in /var/log/syslog file. It will display all matching lines containing searched text as result.
grep "FATAL" /var/log/syslog
Use can also use piped input to grep
cat /var/log/syslog | grep "FATAL" 

Search Without Case Sensitive

Might be the search string is in the different case like fatal or Fatal. Use -i option to instruct grep to ignore case during search. It means it will search for FATAL, fatal and Fatal in any case.
grep -i "FATAL" /var/log/syslog

Search Multiple Strings

You may also need to search some other strings. Like you also want to display lines with “Warning” and “Error”. Use multiple strings to search in a file with grep command with pipe separated.
grep "FATAL|Warning|Error" /var/log/syslog

Search in Multiple Files

As of now, you are searching in a single file. But there can be multiple log files in your system. The Grep command can search in multiple files as well. Search “Error” in file1, file2 file3 etc.
grep "Error" file1 file2 file3 

Search All Files in A Directory

Using wildcard characters, you can search string in all files or files with a specific extension in a directory
 
grep "Error" /var/log/*            #Search in all files
grep "rahul" /var/log/*.log        #Search in specific extension files

Count Lines the String Matched

Use -c to print total number of lines the searched string matched in files. This will not display the matched line content.
grep -c "Error" file

Print Content with Line Number

Sometimes you may also be required to find line numbers of matched content. Use -n to print matched content with line numbers on your screen.
grep -n "rahul" file

Match Whole Line Only

Using -x prints content only matched whole lines
grep -x "rahul" file

Invert search with grep

The -v option only select lines those non-matching with searched string.
grep -v "rahul" /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 "rahul" /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 "rahul" /home/

Search in Specific Extenson Files

Using –include=PATTERN to search for speicifc extension files only with recursive.
grep -R --include="*.php" "rahul" /home/

0 comments:

Post a Comment