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.
Use can also use piped input to grep
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.
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.
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.
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
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.
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.
Match Whole Line Only
Using -x prints content only matched whole lines
Invert search with grep
The -v option only select lines those non-matching with searched string.
Search recursively in multiple files
grep commands also allows to search in file hierarchy recursively. Use -r to search recursively with grep command.
Print Matched Content Filename Only
Using -l prints the matched filename only. its useful with recursively search where lots of search content shows.
Search in Specific Extenson Files
Using –include=PATTERN to search for speicifc extension files only with recursive.
0 comments:
Post a Comment