SlideShare una empresa de Scribd logo
1 de 15
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Unix Operating System
Unix Operating SystemUnix Operating System
Unix Operating System
 
Unix Linux Commands Presentation 2013
Unix Linux Commands Presentation 2013Unix Linux Commands Presentation 2013
Unix Linux Commands Presentation 2013
 
Introduction to Shell script
Introduction to Shell scriptIntroduction to Shell script
Introduction to Shell script
 
Linux systems - Linux Commands and Shell Scripting
Linux systems - Linux Commands and Shell ScriptingLinux systems - Linux Commands and Shell Scripting
Linux systems - Linux Commands and Shell Scripting
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Intro to Linux Shell Scripting
Intro to Linux Shell ScriptingIntro to Linux Shell Scripting
Intro to Linux Shell Scripting
 
structure and union
structure and unionstructure and union
structure and union
 
Linux Directory Structure
Linux Directory StructureLinux Directory Structure
Linux Directory Structure
 
Basic Unix
Basic UnixBasic Unix
Basic Unix
 
Function in C program
Function in C programFunction in C program
Function in C program
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Linux commands
Linux commandsLinux commands
Linux commands
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Know the UNIX Commands
Know the UNIX CommandsKnow the UNIX Commands
Know the UNIX Commands
 
Unix
UnixUnix
Unix
 
Unix ppt
Unix pptUnix ppt
Unix ppt
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
 
Basic linux commands
Basic linux commandsBasic linux commands
Basic linux commands
 

Destacado

Destacado (20)

Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrep
 
Grep
GrepGrep
Grep
 
Learning Grep
Learning GrepLearning Grep
Learning Grep
 
Linux intro 3 grep + Unix piping
Linux intro 3 grep + Unix pipingLinux intro 3 grep + Unix piping
Linux intro 3 grep + Unix piping
 
Unix command-line tools
Unix command-line toolsUnix command-line tools
Unix command-line tools
 
Advance unix(buffer pool)
Advance unix(buffer pool)Advance unix(buffer pool)
Advance unix(buffer pool)
 
Unix
UnixUnix
Unix
 
7th sem it_CSVTU
7th sem it_CSVTU7th sem it_CSVTU
7th sem it_CSVTU
 
Artificial Intelligence Lab File
Artificial Intelligence Lab FileArtificial Intelligence Lab File
Artificial Intelligence Lab File
 
UNIX - Class6 - sed - Detail
UNIX - Class6 - sed - DetailUNIX - Class6 - sed - Detail
UNIX - Class6 - sed - Detail
 
Some basic unix commands
Some basic unix commandsSome basic unix commands
Some basic unix commands
 
Learning sed and awk
Learning sed and awkLearning sed and awk
Learning sed and awk
 
Hill-climbing #2
Hill-climbing #2Hill-climbing #2
Hill-climbing #2
 
Linux 101-hacks
Linux 101-hacksLinux 101-hacks
Linux 101-hacks
 
Hillclimbing search algorthim #introduction
Hillclimbing search algorthim #introductionHillclimbing search algorthim #introduction
Hillclimbing search algorthim #introduction
 
QSpiders - Unix Operating Systems and Commands
QSpiders - Unix Operating Systems  and CommandsQSpiders - Unix Operating Systems  and Commands
QSpiders - Unix Operating Systems and Commands
 
Chapter 2 (final)
Chapter 2 (final)Chapter 2 (final)
Chapter 2 (final)
 
Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}
 
Presentation1 linux os
Presentation1 linux osPresentation1 linux os
Presentation1 linux os
 
Hill climbing
Hill climbingHill climbing
Hill climbing
 

Similar a Grep - A powerful search utility

Unit 8 text processing tools
Unit 8 text processing toolsUnit 8 text processing tools
Unit 8 text processing toolsroot_fibo
 
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressionsAcácio Oliveira
 
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressionsAcácio Oliveira
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linuxTeja Bheemanapally
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linuxTeja Bheemanapally
 
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressionsAcácio Oliveira
 
Cheatsheet: Hex file headers and regex
Cheatsheet: Hex file headers and regexCheatsheet: Hex file headers and regex
Cheatsheet: Hex file headers and regexKasper de Waard
 
Hex file and regex cheat sheet
Hex file and regex cheat sheetHex file and regex cheat sheet
Hex file and regex cheat sheetMartin Cabrera
 
3.7 search text files using regular expressions
3.7 search text files using regular expressions3.7 search text files using regular expressions
3.7 search text files using regular expressionsAcácio Oliveira
 
Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)FrescatiStory
 
Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Ahmed El-Arabawy
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell ScriptDr.Ravi
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1Dr.Ravi
 
Don't Fear the Regex WordCamp DC 2017
Don't Fear the Regex WordCamp DC 2017Don't Fear the Regex WordCamp DC 2017
Don't Fear the Regex WordCamp DC 2017Sandy Smith
 
Lecture 18 - Regular Expressions.pdf
Lecture 18 - Regular Expressions.pdfLecture 18 - Regular Expressions.pdf
Lecture 18 - Regular Expressions.pdfSaravana Kumar
 

Similar a Grep - A powerful search utility (20)

Unix
UnixUnix
Unix
 
Unit 8 text processing tools
Unit 8 text processing toolsUnit 8 text processing tools
Unit 8 text processing tools
 
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions
 
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linux
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linux
 
101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions101 3.7 search text files using regular expressions
101 3.7 search text files using regular expressions
 
Cheatsheet: Hex file headers and regex
Cheatsheet: Hex file headers and regexCheatsheet: Hex file headers and regex
Cheatsheet: Hex file headers and regex
 
Hex file and regex cheat sheet
Hex file and regex cheat sheetHex file and regex cheat sheet
Hex file and regex cheat sheet
 
3.7 search text files using regular expressions
3.7 search text files using regular expressions3.7 search text files using regular expressions
3.7 search text files using regular expressions
 
Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)Tutorial on Regular Expression in Perl (perldoc Perlretut)
Tutorial on Regular Expression in Perl (perldoc Perlretut)
 
Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell Script
 
Spsl II unit
Spsl   II unitSpsl   II unit
Spsl II unit
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1
 
grep.1.pdf
grep.1.pdfgrep.1.pdf
grep.1.pdf
 
grep.1.pdf
grep.1.pdfgrep.1.pdf
grep.1.pdf
 
Don't Fear the Regex WordCamp DC 2017
Don't Fear the Regex WordCamp DC 2017Don't Fear the Regex WordCamp DC 2017
Don't Fear the Regex WordCamp DC 2017
 
Lecture 18 - Regular Expressions.pdf
Lecture 18 - Regular Expressions.pdfLecture 18 - Regular Expressions.pdf
Lecture 18 - Regular Expressions.pdf
 

Último

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 

Último (20)

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 

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