SlideShare a Scribd company logo
2
Most read
4
Most read
7
Most read
grep
A powerful text search utility

1

Presented By
Nirajan Pant
MTech IT
Kathmandu University
2/16/2014
2

What is grep?
A text manipulation program
Used to find pattern in files or text

global regular expression print (: g/RE/p) /
general regular expression parser (grep)
Other text manipulation commands – cut,
tr, awk, sed
grep family - grep, egrep, and fgrep
Type man grep to find list of options
2/16/2014
3

The grep command syntax
General syntax of grep command
grep [-options] pattern [filename]

Examples:
$ grep pattern filename
$ grep pattern file1 file2
$ grep -i desktop /etc/services
$ grep [yf] /etc/group
$ grep –vi tcp /etc/services
$ ip addr show | grep inet
2/16/2014
4

grep and exit status
If the pattern is found, grep returns an exit
status of 0, indicating success
if grep cannot find the pattern, it returns 1
as its exit status
if the file cannot be found, grep returns
an exit status of 2
Note: Other UNIX utilities such as sed and awk do not use the exit
status to indicate the success or failure of locating a pattern; they
report failure only if there is a syntax error in a command
2/16/2014
options

5

Option

Description

-b

Display the block number at the beginning of each line.

-c

Display the number of matched lines.

-h

Display the matched lines, but do not display the
filenames.

-i

Ignore case sensitivity.

-l

Display the filenames, but do not display the matched
lines.

-n

Display the matched lines and their line numbers.

-s

Silent mode.

-v

Display all lines that do NOT match.

-w

Match whole word.

2/16/2014
6

Examples: grep options
 $ grep -i desktop /etc/services
 $ grep –vi tcp /etc/services
 $ grep -v apple fruitlist.txt
 $ grep -l ’main’ *.c
lists the names of all C files in the current directory whose
contents mention „main‟.
 $ grep -r ’hello’ /home/gigi
searches for „hello‟ in all files under the „/home/gigi‟
directory
 $ grep –w ’north’ datafile
Only the line containing the word north is printed, not
northwest
 $ grep -c "Error" logfile.txt

2/16/2014
7

Regular expressions and grep
 Syntax:
grep "REGEX" filename

 Supports three different versions of regular
expression syntax: “basic” (BRE), “extended” (ERE)
and “perl” (PRCE)
 bracket expression: [character_list ] matches any
single character in the list e.g. [01234], [A-D]
Example: grep ‟[A-Z][A-Z] [A-Z]‟ datafile

 Character classes: predefined names of
characters lists within bracket expressions e.g.
[:alnum:], [:alpha:]
2/16/2014
repetition operators:

8
.

The period „.‟ matches any single character

?

The preceding item is optional and matched at most
once.

*

The preceding item will be matched zero or more
times.

+

The preceding item will be matched one or more times.

{n}

The preceding item is matched exactly n times.

{n,}

The preceding item is matched n or more times.

{,m}

The preceding item is matched at most m times. This is
a GNU extension

{n,m}

The preceding item is matched at least n times, but not
more than m times.
2/16/2014
9

Examples: repetition operators
 'l..e' Matches lines containing an l, followed by
two characters, followed by an e
 ' *love' Matches lines with zero or more spaces,
of the preceding characters followed by the
pattern love [here, preceding character is space]
 'o{5}„ Matches if line has 5 o‟s
 'o{5,}„ at least 5 o‟s
 'o{5,10}„ between 5 and 10 o‟s

 $ grep ’5..’ datafile
Prints a line containing the number 5, followed
by a literal period and any single character

2/16/2014
10

The Backslash Characters
 The ‘’ character, when followed by certain ordinary
characters, takes a special meaning:
 ‘b’ Match the empty string at the edge of a word.
 ‘B’ Match the empty string provided it‟s not at the
edge of a word.

 ‘<’ Match the empty string at the beginning of word.
 ‘>’ Match the empty string at the end of word.
 ‘w’ Match word constituent, it is a synonym for
„[_[:alnum:]]‟.

 ‘W’ Match non-word constituent, it is a synonym for
„[^_[:alnum:]]‟.
 ‘s’ Match whitespace, it is a synonym for „[[:space:]]‟.
 ‘S’ Match non-whitespace, it is a synonym for
„[^[:space:]]‟

2/16/2014
11

More with grep
 Anchoring: caret ^ and the dollar sign $ matches
beginning and end of a line respectively
 Alteration: alternate expressions may be joined
by the infix operator |
 Concatenation: regular expressions may be
concatenated
 Precedence: whole expression may be enclosed
in parentheses to override the precedence rules
and form a subexpression
 Basic vs Extended Regular Expressions: use the
backslashed versions ?, +, {, |, (, and )
instead of ?, +, {, |, (, and )
 Environment Variables: affects behavior of grep
e.g. LC_ALL, LC_foo, and LANG
2/16/2014
12

Examples: special characters
 grep '<c...h>' /usr/share/dict/words
list all five-character English dictionary words
starting with "c" and ending in "h"
 grep ‟<north‟ datafile
 grep ‟<north>‟ datafile
 grep Exception logfile.txt | grep -v
ERROR

 grep ’^n’ file Prints all lines beginning with an n
 grep ’4$’ myfile Prints all lines ending with a 4
 grep „bratb‟ datafile matches the separate
word ‘rat’
 grep „BratB‟ datafile matches „crate‟ but not
‘furry rat’
2/16/2014
13

grep with Shell Pipes

Instead of taking its input from a file, grep often gets its input from a pipe.
mpiuser@cp-master:~$ ls -l /home | grep '^d‘
drwx------ 2 root

root

drwxr-xr-x 27 mpiuser
drwxr-xr-x 25 parlab

16384 Jan 28 13:13 lost+found

mpiuser
parlab

4096 Feb 11 11:18 mpiuser
4096 Feb 4 11:08 parlab

drwxr-xr-x 27 parlab-user parcompute 4096 Feb 2 15:51 parlab-user
mpiuser@cp-master:~$ cat /proc/cpuinfo | grep -i model

model

: 23

model name

: Intel(R) Core(TM)2 Duo CPU

model

: 23

model name

: Intel(R) Core(TM)2 Duo CPU

E7400 @ 2.80GHz
E7400 @ 2.80GHz

2/16/2014
14

references
 http://www.computerhope.com/unix/ugrep.htm
 Christopher Negus and Christine Bresnahan. 2012. Linux
Bible (8th ed.). Wiley Publishing, p.128-129, p.157
 Alain Magloire et al. 1 January 2014. GNU Grep: Print lines
matching a pattern (version 2.16)
 http://www.techonthenet.com/unix/basic/grep.php
 http://www.thegeekstuff.com/2009/03/15-practical-unixgrep-command-examples/
 http://www.cs.gsu.edu/~cscyip/csc3320/grep.pdf
2/16/2014
15

Any Questions
Thank you !!!
?
2/16/2014

More Related Content

PPTX
Jammu and kashmir flora and fauna
PPTX
Dynamic memory allocation
PPTX
Infix to postfix conversion
PDF
IBM Infosphere Datastage Interview Questions-1.pdf
PPTX
SQL INJECTION
PPTX
Media Access Control (MAC Layer)
PPTX
Kashmir, Jammu & Kashmir J&K
PPTX
Jammu & kashmir ppt
Jammu and kashmir flora and fauna
Dynamic memory allocation
Infix to postfix conversion
IBM Infosphere Datastage Interview Questions-1.pdf
SQL INJECTION
Media Access Control (MAC Layer)
Kashmir, Jammu & Kashmir J&K
Jammu & kashmir ppt

What's hot (20)

PPTX
Vi editor
PPTX
Filepermissions in linux
PDF
Linux network configuration
PDF
File management
PPT
Shell and its types in LINUX
PPT
Shell programming
PPTX
File in C language
PPT
Class and object in C++
PDF
Graphical Models In Python | Edureka
PPTX
SHELL PROGRAMMING
PPT
Dns ppt
PPTX
Linux network file system (nfs)
PPTX
Basic commands of linux
PPTX
Java servlets
PDF
DNS (Domain Name System)
PDF
Linux basic commands with examples
PPT
Learning sed and awk
PPTX
Linux standard file system
PPTX
Unix
PDF
Advance linux presentation_0702011
Vi editor
Filepermissions in linux
Linux network configuration
File management
Shell and its types in LINUX
Shell programming
File in C language
Class and object in C++
Graphical Models In Python | Edureka
SHELL PROGRAMMING
Dns ppt
Linux network file system (nfs)
Basic commands of linux
Java servlets
DNS (Domain Name System)
Linux basic commands with examples
Learning sed and awk
Linux standard file system
Unix
Advance linux presentation_0702011
Ad

Viewers also liked (20)

PPT
Regular Expressions grep and egrep
DOCX
Learning Grep
PDF
Linux intro 3 grep + Unix piping
PPT
Unix command-line tools
DOC
Advance unix(buffer pool)
PDF
PDF
7th sem it_CSVTU
DOCX
Artificial Intelligence Lab File
PPS
UNIX - Class6 - sed - Detail
DOC
Some basic unix commands
PPTX
Hill-climbing #2
PDF
Linux 101-hacks
ODP
Hillclimbing search algorthim #introduction
PPS
QSpiders - Unix Operating Systems and Commands
DOC
Chapter 2 (final)
PPT
Heuristic Search Techniques {Artificial Intelligence}
PPT
Presentation1 linux os
PPT
Hill climbing
PPT
Basic command ppt
Regular Expressions grep and egrep
Learning Grep
Linux intro 3 grep + Unix piping
Unix command-line tools
Advance unix(buffer pool)
7th sem it_CSVTU
Artificial Intelligence Lab File
UNIX - Class6 - sed - Detail
Some basic unix commands
Hill-climbing #2
Linux 101-hacks
Hillclimbing search algorthim #introduction
QSpiders - Unix Operating Systems and Commands
Chapter 2 (final)
Heuristic Search Techniques {Artificial Intelligence}
Presentation1 linux os
Hill climbing
Basic command ppt
Ad

Similar to Grep - A powerful search utility (20)

DOCX
Unix
PPT
grep and egrep linux presentation for lecture
PDF
Unit 8 text processing tools
PPT
101 3.7 search text files using regular expressions
PPT
101 3.7 search text files using regular expressions
PPTX
PRACTICAL -UNIX, shell programs, shell commands
PPTX
PRACTICAL -UNIX, shell commands in unix, practice commands on shell
PPTX
PRACTICAL -UNIX, main unix commands in practice
DOCX
15 practical grep command examples in linux
DOCX
15 practical grep command examples in linux
PPT
101 3.7 search text files using regular expressions
PDF
Hex file and regex cheat sheet
PDF
Cheatsheet: Hex file headers and regex
PPT
3.7 search text files using regular expressions
PDF
Tutorial on Regular Expression in Perl (perldoc Perlretut)
PDF
Course 102: Lecture 13: Regular Expressions
PPT
Perl Presentation
PPT
Talk Unix Shell Script
PPT
Spsl II unit
PPT
Talk Unix Shell Script 1
Unix
grep and egrep linux presentation for lecture
Unit 8 text processing tools
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions
PRACTICAL -UNIX, shell programs, shell commands
PRACTICAL -UNIX, shell commands in unix, practice commands on shell
PRACTICAL -UNIX, main unix commands in practice
15 practical grep command examples in linux
15 practical grep command examples in linux
101 3.7 search text files using regular expressions
Hex file and regex cheat sheet
Cheatsheet: Hex file headers and regex
3.7 search text files using regular expressions
Tutorial on Regular Expression in Perl (perldoc Perlretut)
Course 102: Lecture 13: Regular Expressions
Perl Presentation
Talk Unix Shell Script
Spsl II unit
Talk Unix Shell Script 1

Recently uploaded (20)

PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
Indian roads congress 037 - 2012 Flexible pavement
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
Hazard Identification & Risk Assessment .pdf
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PPTX
20th Century Theater, Methods, History.pptx
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
advance database management system book.pdf
PDF
HVAC Specification 2024 according to central public works department
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PPTX
Computer Architecture Input Output Memory.pptx
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Indian roads congress 037 - 2012 Flexible pavement
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Hazard Identification & Risk Assessment .pdf
AI-driven educational solutions for real-life interventions in the Philippine...
20th Century Theater, Methods, History.pptx
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
advance database management system book.pdf
HVAC Specification 2024 according to central public works department
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
Computer Architecture Input Output Memory.pptx
Unit 4 Computer Architecture Multicore Processor.pptx
Introduction to pro and eukaryotes and differences.pptx
LDMMIA Reiki Yoga Finals Review Spring Summer

Grep - A powerful search utility

  • 1. grep A powerful text search utility 1 Presented By Nirajan Pant MTech IT Kathmandu University 2/16/2014
  • 2. 2 What is grep? A text manipulation program Used to find pattern in files or text global regular expression print (: g/RE/p) / general regular expression parser (grep) Other text manipulation commands – cut, tr, awk, sed grep family - grep, egrep, and fgrep Type man grep to find list of options 2/16/2014
  • 3. 3 The grep command syntax General syntax of grep command grep [-options] pattern [filename] Examples: $ grep pattern filename $ grep pattern file1 file2 $ grep -i desktop /etc/services $ grep [yf] /etc/group $ grep –vi tcp /etc/services $ ip addr show | grep inet 2/16/2014
  • 4. 4 grep and exit status If the pattern is found, grep returns an exit status of 0, indicating success if grep cannot find the pattern, it returns 1 as its exit status if the file cannot be found, grep returns an exit status of 2 Note: Other UNIX utilities such as sed and awk do not use the exit status to indicate the success or failure of locating a pattern; they report failure only if there is a syntax error in a command 2/16/2014
  • 5. options 5 Option Description -b Display the block number at the beginning of each line. -c Display the number of matched lines. -h Display the matched lines, but do not display the filenames. -i Ignore case sensitivity. -l Display the filenames, but do not display the matched lines. -n Display the matched lines and their line numbers. -s Silent mode. -v Display all lines that do NOT match. -w Match whole word. 2/16/2014
  • 6. 6 Examples: grep options  $ grep -i desktop /etc/services  $ grep –vi tcp /etc/services  $ grep -v apple fruitlist.txt  $ grep -l ’main’ *.c lists the names of all C files in the current directory whose contents mention „main‟.  $ grep -r ’hello’ /home/gigi searches for „hello‟ in all files under the „/home/gigi‟ directory  $ grep –w ’north’ datafile Only the line containing the word north is printed, not northwest  $ grep -c "Error" logfile.txt 2/16/2014
  • 7. 7 Regular expressions and grep  Syntax: grep "REGEX" filename  Supports three different versions of regular expression syntax: “basic” (BRE), “extended” (ERE) and “perl” (PRCE)  bracket expression: [character_list ] matches any single character in the list e.g. [01234], [A-D] Example: grep ‟[A-Z][A-Z] [A-Z]‟ datafile  Character classes: predefined names of characters lists within bracket expressions e.g. [:alnum:], [:alpha:] 2/16/2014
  • 8. repetition operators: 8 . The period „.‟ matches any single character ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension {n,m} The preceding item is matched at least n times, but not more than m times. 2/16/2014
  • 9. 9 Examples: repetition operators  'l..e' Matches lines containing an l, followed by two characters, followed by an e  ' *love' Matches lines with zero or more spaces, of the preceding characters followed by the pattern love [here, preceding character is space]  'o{5}„ Matches if line has 5 o‟s  'o{5,}„ at least 5 o‟s  'o{5,10}„ between 5 and 10 o‟s  $ grep ’5..’ datafile Prints a line containing the number 5, followed by a literal period and any single character 2/16/2014
  • 10. 10 The Backslash Characters  The ‘’ character, when followed by certain ordinary characters, takes a special meaning:  ‘b’ Match the empty string at the edge of a word.  ‘B’ Match the empty string provided it‟s not at the edge of a word.  ‘<’ Match the empty string at the beginning of word.  ‘>’ Match the empty string at the end of word.  ‘w’ Match word constituent, it is a synonym for „[_[:alnum:]]‟.  ‘W’ Match non-word constituent, it is a synonym for „[^_[:alnum:]]‟.  ‘s’ Match whitespace, it is a synonym for „[[:space:]]‟.  ‘S’ Match non-whitespace, it is a synonym for „[^[:space:]]‟ 2/16/2014
  • 11. 11 More with grep  Anchoring: caret ^ and the dollar sign $ matches beginning and end of a line respectively  Alteration: alternate expressions may be joined by the infix operator |  Concatenation: regular expressions may be concatenated  Precedence: whole expression may be enclosed in parentheses to override the precedence rules and form a subexpression  Basic vs Extended Regular Expressions: use the backslashed versions ?, +, {, |, (, and ) instead of ?, +, {, |, (, and )  Environment Variables: affects behavior of grep e.g. LC_ALL, LC_foo, and LANG 2/16/2014
  • 12. 12 Examples: special characters  grep '<c...h>' /usr/share/dict/words list all five-character English dictionary words starting with "c" and ending in "h"  grep ‟<north‟ datafile  grep ‟<north>‟ datafile  grep Exception logfile.txt | grep -v ERROR  grep ’^n’ file Prints all lines beginning with an n  grep ’4$’ myfile Prints all lines ending with a 4  grep „bratb‟ datafile matches the separate word ‘rat’  grep „BratB‟ datafile matches „crate‟ but not ‘furry rat’ 2/16/2014
  • 13. 13 grep with Shell Pipes Instead of taking its input from a file, grep often gets its input from a pipe. mpiuser@cp-master:~$ ls -l /home | grep '^d‘ drwx------ 2 root root drwxr-xr-x 27 mpiuser drwxr-xr-x 25 parlab 16384 Jan 28 13:13 lost+found mpiuser parlab 4096 Feb 11 11:18 mpiuser 4096 Feb 4 11:08 parlab drwxr-xr-x 27 parlab-user parcompute 4096 Feb 2 15:51 parlab-user mpiuser@cp-master:~$ cat /proc/cpuinfo | grep -i model model : 23 model name : Intel(R) Core(TM)2 Duo CPU model : 23 model name : Intel(R) Core(TM)2 Duo CPU E7400 @ 2.80GHz E7400 @ 2.80GHz 2/16/2014
  • 14. 14 references  http://www.computerhope.com/unix/ugrep.htm  Christopher Negus and Christine Bresnahan. 2012. Linux Bible (8th ed.). Wiley Publishing, p.128-129, p.157  Alain Magloire et al. 1 January 2014. GNU Grep: Print lines matching a pattern (version 2.16)  http://www.techonthenet.com/unix/basic/grep.php  http://www.thegeekstuff.com/2009/03/15-practical-unixgrep-command-examples/  http://www.cs.gsu.edu/~cscyip/csc3320/grep.pdf 2/16/2014
  • 15. 15 Any Questions Thank you !!! ? 2/16/2014