grep – A utility for searching for specified text in files, file names, etc. from the command line.
You can search using grep, even for example in the output of some command:
COMMAND | grep TEXT
You can calculate the number of lines where the specified text occurs:
grep -c TEXT FILENAME
grep TEXT FILENAME | wc -l
grep -o 'TEXT' FILENAME | uniq -c
To search and display the lines with the specified text, execute:
grep TEXT FILE
Full-text search – Search for text in all files of the specified directory:
grep TEXT /DIRECTORY/*
grep -r TEXT /DIRECTORY/*
grep -rnw '/dir/' -e 'TEXT'
Full-text search – Search for text in all files of the specified directory (-F indicates that there should be an exact match to the text, otherwise, for example, instead of “test.ixnfo.com” it will also find “test@ixnfo.com”, etc.):
grep -Fr TEXT /dir/*
Search only for the whole specified word:
grep -w WORD FILE
Display the lines where the specified words occur:
grep -E "(WORD|WORD|WORD)" FILE
Display lines where the specified words occur several times:
grep -E "(WORD|WORD).*\1"
Display also the lines after the search, for example 5 lines:
grep -A 5 WORD FILE
Or the lines before the search:
grep -B 5 WORD FILE
Show lines where the WORD1, WORD2, WORD3 occurs:
grep WORD[1-3] FILE
Show all lines where the IP address occurs:
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" FILE
Show lines where capital letters occur:
grep "[[:upper:]]" FILE
Show lines where the specified word appears with a tab on both sides:
grep "[[:blank:]]WORD[[:blank:]]" FILE
grep " WORD " FILE
Find and replace the text with another command:
grep 'the_text_we_are_looking_for' -P -R -I -l * | xargs sed -i 's/the_text_we_are_looking_for/the text to which we replace/g'
I’ll describe some startup options:
-b (displaying the block number in which the fragment was found, the blocks are numbered from 0)
-c (display only the number of rows in which the fragment was found)
-r (search also in subdirectories)
-n (displays line number)
-h (hides the filenames before the found fragments, when the search is performed on several files)
-l (display only file names where the fragment occurs)
-i (ignoring the case of characters, that is, the big and small letters are equal when searching)
-s (hides messages about nonexistent or inaccessible files)
-v (displays all lines except the specified sample)