Grep grep Examples Linux

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 “”

grep -r "" /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

Grep grep Examples Linux TCP/IP Ubuntu

Detecting listening network ports on Linux

It is importand to check for ports that are open and there are not needed.

For a list of network ports that are open you can use the following commands:

netstat -tulp or
lsof -i -n | egrep ‘COMMAND|LISTEN|UDP’

Or, you are not limited to netstat or lsof but you can always use a port scanner, telnet or nc to list open/close ports.