grep
grep linux command cheatsheet by Thamizhiniyan C S
Introduction
The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression.
Important Flags
-R
Does a recursive grep search for the files inside the folders(if found in the specified path for pattern search; else grep won't traverse directory for searching the pattern you specify)
-h
If you're grepping recursively in a directory, this flag disables the prefixing of filenames in the results.
-c
This flag won't list you the pattern only list an integer value, that how many times the pattern was found in the file/folder.
-i
Specifies grep to search for the PATTERN while IGNORING the case
-l
Will only list the filename instead of pattern found in it.
-n
It will list the lines with their line number in the file containing the pattern.
-v
This flag prints all the lines that are NOT containing the pattern
-E
This flag we already read above... will consider the PATTERN as a regular expression to find the matching strings.
-e
The official documentation says, it can be used to specify multiple patterns and if any string matches with the pattern(s) it will list it.
Examples
grep "literal_string" filenameSearch for the given string in a single file
grep "string" FILE_PATTERNChecking for the given string in multiple files
grep -i "string" FILECase insensitive search
grep "REGEX" filenameMatch regular expression in files
grep -iw "is" demo_fileChecking for full words, not for sub-strings using grep -w
grep -A "string" FILENAMEDisplay N lines after match
grep -B "string" FILENAMEDisplay N lines before match
grep -C "string" FILENAMEDisplay N lines around match
grep -r "ramesh" *Searching in all files recursively using grep -r
grep -v "go" demo_textInvert match using grep -v
grep -v -e "pattern" -e "pattern"Display the lines which does not matches all the given pattern
grep -c "pattern" filenameCounting the number of matches using grep -c
grep -l this demo_*Display only the file names which matches the given pattern using grep -l
grep -o "is.*line" demo_fileShow only the matched string
grep -o -b "pattern" fileShow the position of match in the line
grep -n "go" demo_textShow line number while displaying the output using grep -n
grep -iRl [directory path/keyword]Find files with a specific keyword
Last updated
Was this helpful?