Grep is one of the most used Linux commands from the command line. The grep command is used to search text or search a given file for lines containing a match to the given strings or words. It is very useful when you want to search for text inside files. You can also use regular expressions when filtering files.
1. The basic use of grep commands:
grep 'word' filename
grep 'word' file1 file2 file3
grep 'string1 string2' filename
grep "REGEX" filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName
2. Find a word in a file using grep command
grep 'text to find' /path/to/your/file
#sample:
grep 'find me' /home/ivan/public_html/ivan.php
3. Recursive search in directories
grep -r 'text to find' /path/to/your/directory
#sample:
grep -r 'find me' /home/ivan/public_html/
#You can add -l to show the filename
grep -rl 'find me' /home/ivan/public_html/
#you can print the file name for each match with -H option
grep -rH 'find me' /home/ivan/public_html/
4. Ignore word case
grep -i 'text to find' /path/to/your/directory
#sample:
grep -i 'find me' /home/ivan/public_html/
5. Search 2 different words:
egrep -w 'word1|word2' /path/to/file
6. You can pipe grep with other Linux commands, for example:
dmesg | egrep '(s|h)d[a-z]'
cat /proc/cpuinfo | grep -i 'Model'
grep -i 'Model' /proc/cpuinfo
#a slightly more complex example:
find . | awk '!/((.jpeg)|(.jpg)|(.png))$/ {print $0;}' | xargs grep "B206"
