Home » linux-commands » Most useful practical instances of grep command.

Most useful practical instances of grep command.

Grep is a command-line tool for searching text data sets for lines matching a usual expression fashioned by Ken Thompson. grep command was initially developed for the Unix operating system, but is offered now for all Unix-like systems. The grep name originally comes from the ed command g/re/p (globally search a regular expression and print), which has the same effect: doing a global search with the regular expression and printing all matching lines.

1. Grep options are the –A and –B switches, which displays the matched line and number of lines either that come before or after the search string. The man page provides a more comprehensive explanation, I find it easiest to

remember the options as –A = after, and –B = before

root@linuxpcfix [~]# ifconfig | grep –A 5 eth0
root@linuxpcfix [~]# ifconfig | grep -B 2 Down

2. The –n option for grep is very useful when debugging files during assemble errors. It shows the line number in the file of the given search string:

root@linuxpcfix [~]# grep –n “main” setup.py

3. If you would like to search for a string in the current directory along with all of the subdirectories, you can specify the –r option to search recursively also if you want to symlinks you can use -R

root@linuxpcfix [~]# grep –r “function” *

4. Passing the –w option to grep searches for the entire pattern:

root@linuxpcfix [~]# ifconfig | grep –w “RUNNING”

5. Deserving some mention are derivatives of grep command. The foremost is zgrep, which, just like to zcat, is for apply on gzipped files. It use the same options as grep and is used in the same way:

root@linuxpcfix [~]# zgrep –i error /var/log/syslog.2.gz

6. List all directories in a folder

root@linuxpcfix [~]#ls -laR | egrep ^d

7. With option -c along with -w will output the total number of Only lines containing the distinct word “hope” will be matched. Lines in which “hope” is part of a word will not be matched.

root@linuxpcfix [~]#grep -cw “hope” myfile.txt

Exit Status

The exit status is 0 if selected lines are matched, and 1 if not match. If an error occurred the exit status is 2.

About

I am founder and webmaster of www.linuxpcfix.com and working as a Sr. Linux Administrator (Expertise on Linux/Unix & Cloud Server) and have been in the industry from last 7 years.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Time limit is exhausted. Please reload the CAPTCHA.

Categorized Tag Cloud