Tips to use Grep Command in Linux

Grep is one of the most use Linux command from command line. The grep command use to search text or searches the given file for lines containing a match to the given strings or words. Very useful if you want to search a text inside the files. And you can use regular expression in filtering the files.

1. The basic use fo 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
grep 'find me' /home/ivan/public_html/ivan.php

3. Recursive search in directories

grep -r 'text to find' /path/to/your/directory
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
grep -i 'find me' /home/ivan/public_html/

5. Search 2 different words:

<code>egrep -w 'word1|word2' /path/to/file</code>

6. You can pipes Grep with other Linux command, sample:

dmesg | egrep '(s|h)d[a-z]'
cat /proc/cpuinfo | grep -i 'Model'
grep -i 'Model' /proc/cpuinfo
#little but complex sample:
find . | awk '!/((\.jpeg)|(\.jpg)|(\.png))$/ {print $0;}' | xargs grep "B206"


  1. Lize says:

    Thank you very much Ivan. You save my time!

Give me your feedback

This site uses Akismet to reduce spam. Learn how your comment data is processed.