Loading

Sunday, January 17, 2010

How To Use grep Command In Linux

The grep command searches the given file for lines containing a match to the given strings or words. By default, grep prints the matching lines. grep can be used to search for lines of text that match one or many regular expressions, and outputs only the matching lines.

grep Syntax
grep 'word' filename
grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'
grep Examples
  • Use grep to search a file
    Search /etc/passwd for user admin:
grep admin /etc/passwd
You can force grep to ignore word case i.e. match admin, Admin, ADMIN or any other combination with the -i option:
grep -i "admin" /etc/passwd
  • Use grep recursively
    You can search recursively with grep, i.e. read all files under each directory for a string "10.10.1.25"
grep -r "10.10.1.25" /etc
  • Use grep to search two different words
grep -w 'word1|word2' /path
  • Count number of lines where word(s) is/are matched
    grep can report the number of times that the pattern has been matched for each file using -c (count) option:
grep -c 'word' /path
Also note that you can use -n option, which causes grep to precede each line of output with the number of the line in the text file from which it was obtained:
grep -n 'word' /path
  • Grep invert match
    The -v option can be used to print inverts of the match; that is, it matches only those lines that do not contain the given word. For example print all lines that do not contain the word invert:
grep -v invert /path
  • Display CPU Model Name With grep
grep -i 'model' /proc/cpuinfo
  • Use grep to just list the names of matching files
grep -l 'word' *.c*
  • Set grep to display output in colors
grep --color admin /etc/passwd

No comments:

Post a Comment