Grep command examples

/ Category: Tips and Tricks / Comments: None

Spread the love

Grep is one of the most used commands in Unix (or Linux). The name “grep” means “general regular expression parser” The grep command is used to search for text strings or regular expressions within one or more files. It can be very useful in your daily administration work on your Linux Cloud Hosting account.


The basic syntax of grep is:

grep pattern target_file

OK, now that we have the theory, let’s see some practical examples.

1. Searching for a text string in one file

grep 'root' /etc/passwd

2. Searching for a string in multiple files

grep 'root' /etc/*

The wild card matches all files in the /etc/directory

3. Showing matching line numbers (-n)

grep -n 'root' /etc/passwd

4. Counting the number of matches (-c)

grep -c 'root' /etc/passwd

5. Recursive search (-r or -R)

grep -r "string" /home/

Search for the string ‘string’ in all the files in the home directory and all its subdirectories.

6. Invert match (-v)

grep -v 'root' /etc/passwd

Displays the lines which does not matches the given string

7. Display only the file names which matches the given pattern (-l)

grep -rl "string" /home/

8. Search for full words not partial matches within words (-w)

grep -w "fullstring" /home/

9. Show only the matched string, not the whole line (-o)

grep -o "fstring" /home/

10. Advanced usage of grep

– find out process pid

ps aux | grep someprocess

– multi patterns

grep -iE "(something|somethingelse)" file

– determine which services are enabled at boot

chkconfig --list | grep $(runlevel | awk '{ print $2}'):on

– search for IP addresses

grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/maillog

Be the first to write a comment.

Your feedback