You are on page 1of 28

MENU

Regular Expressions in Grep Command with 10


Examples Part I
by SA SI KA LA on JA NUA RY 4 , 2 0 1 1
10

Like

17

Tweet

Regular expressions are used to


search and manipulate the text,
based on the patterns. Most of the
Linux commands and programming
languages use regular expression.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Grep command is used to search for


a specific string in a file. Please refer
our earlier article for 15 practical grep command examples.
You can also use regular expressions with grep command when you want to search
for a text containing a particular pattern. Regular expressions search for the
patterns on each line of the file. It simplifies our search operation.
This articles is part of a 2 article series.
This part 1 article covers grep examples for simple regular expressions. The future
part 2 article will cover advanced regular expression examples in grep.
Let us take the file /var/log/messages file which will be used in our examples.

Example 1. Beginning of line ( ^ )


In grep command, caret Symbol ^ matches the expression at the start of a line. In
the following example, it displays all the line which starts with the Nov 10. i.e All
the messages logged on November 10.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

$ grep "^Nov 10" messages.1


Nov 10 01:12:55 gs123 ntpd[2241]: time reset +0.177479 s
Nov 10 01:17:17 gs123 ntpd[2241]: synchronized to LOCAL(0), stratum 10
Nov 10 01:18:49 gs123 ntpd[2241]: synchronized to 15.1.13.13, stratum 3
Nov 10 13:21:26 gs123 ntpd[2241]: time reset +0.146664 s
Nov 10 13:25:46 gs123 ntpd[2241]: synchronized to LOCAL(0), stratum 10
Nov 10 13:26:27 gs123 ntpd[2241]: synchronized to 15.1.13.13, stratum 3

The ^ matches the expression in the beginning of a line, only if it is the first
character in a regular expression. ^N matches line beginning with N.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 2. End of the line ( $)


Character $ matches the expression at the end of a line. The following command
will help you to get all the lines which ends with the word terminating.

$ grep "terminating.$" messages


Jul 12 17:01:09 cloneme kernel: Kernel log daemon terminating.
Oct 28 06:29:54 cloneme kernel: Kernel log daemon terminating.

From the above output you can come to know when all the kernel log has got
terminated. Just like ^ matches the beginning of the line only if it is the first
character, $ matches the end of the line only if it is the last character in a regular
expression.

Example 3. Count of empty lines ( ^$ )


Using ^ and $ character you can find out the empty lines available in a file. ^$
specifies empty line.

$ grep -c
open in browser PRO version

"^$" messages anaconda.log

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

messages:0
anaconda.log:3

The above commands displays the count of the empty lines available in the
messages and anaconda.log files.

Example 4. Single Character (.)


The special meta-character . (dot) matches any character except the end of the
line character. Let us take the input file which has the content as follows.

$ cat input
1. first line
2. hi hello
3. hi zello how are you
4. cello
5. aello
6. eello
7. last line

Now let us search for a word which has any single character followed by ello. i.e
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

hello, cello etc.,

$ grep ".ello" input


2. hi hello
3. hi zello how are you
4. cello
5. aello
6. eello

In case if you want to search for a word which has only 4 character you can give
grep -w . where single dot represents any single character.

Example 5. Zero or more occurrence (*)


The special character * matches zero or more occurrence of the previous
character. For example, the pattern 1* matches zero or more 1.
The following example searches for a pattern kernel: * i.e kernel: and zero or
more occurrence of space character.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

$ grep "kernel: *." *

messages.4:Jul 12 17:01:02 cloneme kernel: ACPI: PCI interrupt for device 0000:00:11.0 di
messages.4:Oct 28 06:29:49 cloneme kernel: ACPI: PM-Timer IO Port: 0x1008
messages.4:Oct 28 06:31:06 btovm871 kernel:

sda: sda1 sda2 sda3

messages.4:Oct 28 06:31:06 btovm871 kernel: sd 0:0:0:0: Attached scsi disk sda


.
.

In the above example it matches for kernel and colon symbol followed by any
number of spaces/no space and . matches any single character.

Example 6. One or more occurrence (\+)


The special character \+ matches one or more occurrence of the previous
character. \+ matches at least one or more space character.
If there is no space then it will not match. The character + comes under
extended regular expression. So you have to escape when you want to use it with
the grep command.

$ cat input
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

hi hello
hi

hello how are you

hihello

$ grep "hi \+hello" input


hi hello
hi

hello how are you

In the above example, the grep pattern matches for the pattern hi, followed by
one or more space character, followed by hello.
If there is no space between hi and hello it wont match that. However, * character
matches zero or more occurrence.
hihello will be matched by * as shown below.

$ grep "hi *hello" input


hi hello
hi

hello how are you

hihello
$
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 7. Zero or one occurrence (\?)


The special character ? matches zero or one occurrence of the previous
character. 0? matches single zero or nothing.

$ grep "hi \?hello" input


hi hello
hihello

hi \?hello matches hi and hello with single space (hi hello) and no space (hihello).
The line which has more than one space between hi and hello did not get matched
in the above command.

Example 8.Escaping the special character (\)


If you want to search for special characters (for example: * , dot) in the content
you have to escape the special character in the regular expression.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

$ grep "127\.0\.0\.1"

/var/log/messages.4

Oct 28 06:31:10 btovm871 ntpd[2241]: Listening on interface lo, 127.0.0.1#123 Enabled

Example 9. Character Class ([0-9])


The character class is nothing but list of characters mentioned with in the square
bracket which is used to match only one out of several characters.

$ grep -B 1 "[0123456789]\+ times" /var/log/messages.4


Oct 28 06:38:35 btovm871 init: open(/dev/pts/0): No such file or directory
Oct 28 06:38:35 btovm871 last message repeated 2 times

Oct 28 06:38:38 btovm871 pcscd: winscard.c:304:SCardConnect() Reader E-Gate 0 0 Not Found


Oct 28 06:38:38 btovm871 last message repeated 3 times

Repeated messages will be logged in messages logfile as last message repeated n


times. The above example searches for the line which has any number (0to9)
followed by the word times. If it matches it displays the line before the matched
line and matched line also.
With in the square bracket, using hyphen you can specify the range of characters.
Like [0123456789] can be represented by [0-9]. Alphabets range also can be
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

specified such as [a-z],[A-Z] etc. So the above command can also be written as

$ grep -B 1 "[0-9]\+ times" /var/log/messages.4

Example 10. Exception in the character class


If you want to search for all the characters except those in the square bracket,
then use ^ (Caret) symbol as the first character after open square bracket. The
following example searches for a line which does not start with the vowel letter
from dictionary word file in linux.

$ grep -i

"^[^aeiou]" /usr/share/dict/linux.words

1080
10-point
10th
11-point
12-point
16-point
18-point
1st
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

First caret symbol in regular expression represents beginning of the line. However,
caret symbol inside the square bracket represents except i.e match except
everything in the square bracket.
10

Tweet

Like

17

> Add your comment

If you enjoyed this article, you might also like..


1. 50 Linux Sysadmin Tutorials

Awk Introduction 7 Awk Print

2. 50 Most Frequently Used Linux

Examples

Commands (With Examples)


3. Top 25 Best Linux Performance
Monitoring and Debugging Tools
4. Mommy, I found it! 15 Practical Linux
Find Command Examples
5. Linux 101 Hacks 2nd Edition eBook

Advanced Sed Substitution


Examples
8 Essential Vim Editor Navigation
Fundamentals
25 Most Frequently Used Linux
IPTables Rules Examples
Turbocharge PuTTY with 12
Powerful Add-Ons

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

{ 17 comments add one }


Felix Frank

January 4, 201 1 , 6:27 am

. is not at all an expression for an exactly 4-letter word (not even


with grep -w) and will not work.
For that, youd need a horror like \b.\B.\B.\B.\b.
Fortunately, its an unlikely use case.
LI NK
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

linuxboy

January 4, 201 1 , 8:1 4 am

hello Ramesh Natarajan


Im reading all your Blog and like your articles style,command with Examples.
thanks for your sharing.
LI NK

dj

January 4, 201 1 , 2:48 pm

I often use the -E, extended-regexp option. It posix compliant.


http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
LI NK

Cissy

January 4, 201 1 , 7 :50 pm

Thanks for sharing


I learned a lot..
lol
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

LI NK

alok chaubey

October 3, 201 1 , 5:45 pm

yeP. your work in the field of linux is truly appreciable


LI NK

Kashif

January 24, 201 2, 3:1 0 am

Worked for me but can you please tell how to grep % from the below
syntax
PING=$(ping -c 10 192.168.1.1 | grep -w
statistics|Time|100\\%|90\\%|80\\%|70\\%|60\\%|50\\%|40\\%|30\\%|20\
\%|10\\%)
I am doing this because I dont want a report if 10 packets are successfully sent
and there is 0% packet loss.
Thanks
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

LI NK

Prasanna N

August 6, 201 2, 1 1 :41 am

Ramesh, I just found your site yesterday.


This is exactly what I was searching for to learn all the unixy stuff.
The articles are great and I have already learnt a lot!
Thanks immensely.
LI NK

Ankit Gupta

February 1 4, 201 3, 1 :04 am

A very good/handy article. Looking for the sequel of the article.


LI NK

kishore
open in browser PRO version

May 22, 201 3, 5:04 am

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

can you provide an example for exception of blank spaces


LI NK

Nilesh

May 28, 201 3, 1 0:01 pm

Kishore,
Theres -v option which inverts the search. So something like below should work.
grep -v ^$ filename
LI NK

amrutha

May 1 1 , 201 4, 1 1 :37 pm

for the beginners its very useful,clear explanation


LI NK

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Anonymous

June 3, 201 4, 7 :27 am

awesome covers majority of the pattren


LI NK

Vasanth

August 1 4, 201 4, 1 :1 7 pm

Hello Ramesh,
I really appreciate the effort you have taken in posting this on the Internet.
I have about 20 years of experience in the IT industry and I loved these
examples.
Thanks to you
LI NK

Vipin

December 1 8, 201 4, 4:38 pm

I am new to Linux,these tutorials help quite a lot. Thanks!!

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

LI NK

Sugan

April 21 , 201 5, 7 :06 am

Hi, Its easy to learn here.. Thanks.


LI NK

saurabh

Nov ember 1 7 , 201 5, 8:42 am

grep -i ^[^aeiou] /usr/share/dict/linux.words


Command is not worning in centos. the results shows all the characters starting
with aeiou.
LI NK

sumit

Nov ember 1 8, 201 5, 1 :56 pm

It was very helpful. Thank you for explaining. Could have been more
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

useful if it would include regular expression {n,m} as well.


LI NK

Leave a Comment
Name

Email

Website

Comment

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Submit

Notify me of followup comments via e-mail

Next post: 9 UNIX / Linux tput Examples: Control Your Terminal Color and
Cursor
Previous post: Happy New Year 2011 From Geek and the Doll

RSS | Email | Twitter | Facebook | Google+


Search
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

EBOOKS
Linux 101 Hacks 2nd Edition eBook - Practical Examples to Build a Strong Foundation in Linux
Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well

open in browser PRO version

The Geek Stuff

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

The Geek Stuff


14,982 likes

Like Page

Share

Be the first of your friends to like this

POPULAR POSTS
12 Amazing and Essential Linux Books To Enrich Your Brain and Library
50 UNIX / Linux Sysadmin Tutorials
50 Most Frequently Used UNIX / Linux Commands (With Examples)
How To Be Productive and Get Things Done Using GTD
30 Things To Do When you are Bored and have a Computer
Linux Directory Structure (File System Structure) Explained with Examples
Linux Crontab: 15 Awesome Cron Job Examples
Get a Grip on the Grep! 15 Practical Grep Command Examples
Unix LS Command: 15 Practical Examples
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

15 Examples To Master Linux Command Line History


Top 10 Open Source Bug Tracking System
Vi and Vim Macro Tutorial: How To Record and Play
Mommy, I found it! -- 15 Practical Linux Find Command Examples
15 Awesome Gmail Tips and Tricks
15 Awesome Google Search Tips and Tricks
RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
Can You Top This? 15 Practical Linux Top Command Examples
Top 5 Best System Monitoring Tools
Top 5 Best Linux OS Distributions
How To Monitor Remote Linux Host using Nagios 3.0
Awk Introduction Tutorial 7 Awk Print Examples
How to Backup Linux? 15 rsync Command Examples
The Ultimate Wget Download Guide With 15 Awesome Examples
Top 5 Best Linux Text Editors
Packet Analyzer: 15 TCPDUMP Command Examples
The Ultimate Bash Array Tutorial with 15 Examples
3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
Unix Sed Tutorial: Advanced Sed Substitution Examples
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

UNIX / Linux: 10 Netstat Command Examples


The Ultimate Guide for Creating Strong Passwords
6 Steps to Secure Your Home Wireless Network
Turbocharge PuTTY with 12 Powerful Add-Ons

CATEGORIES
Linux Tutorials
Vim Editor
Sed Scripting
Awk Scripting
Bash Shell Scripting
Nagios Monitoring
OpenSSH
IPTables Firewall
Apache Web Server
MySQL Database
Perl Programming
Google Tutorials
Ubuntu Tutorials
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

PostgreSQL DB
Hello World Examples
C Programming
C++ Programming
DELL Server Tutorials
Oracle Database
VMware Tutorials

Ramesh Natarajan
Follow

A BOUT T H E G EEK S T UFF


My name is Ramesh Natarajan.
I will be posting instruction guides,
how-to, troubleshooting tips and
tricks on Linux, database,
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

hardware, security and web. My


focus is to write articles that will
either teach you or help you resolve a problem.
Read more about Ramesh Natarajan and the blog.

C ON T A C T U S
Email Me : Use this Contact Form to get in touch
me with your comments, questions or suggestions
about this site. You can also simply drop me a line
to say hello!.
Follow us on Google+
Follow us on Twitter
Become a fan on Facebook

S UPPORT U S
Support this blog by purchasing one of my ebooks.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Bash 101 Hacks eBook


Sed and Awk 101 Hacks eBook
Vim 101 Hacks eBook
Nagios Core 3 eBook

Copy right 2008201 5 Ramesh Natarajan. All rights reserv ed | Terms of Serv ice

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

You might also like