Sunteți pe pagina 1din 25

grep,egrep,sed

Grep
y Searchesfortextinafile y Cansearchforsimplewords:chair y Canlookforregularexpressions;morecomplex

characterstringssuchaschairfollowedbyany numberofspaces,followedbyadigitorlowercase letter. y GlobalRegularExpressionPrint

Whatcanitdo?
y Copynextinputlineintopatternspace y Applyregularexpressiontopatterspace y Copiesmatchestooutput

Copy Apply Output

grepFamily
egrep
Allowsformorecomplexpatterns

fgrep

Goodforsearchingtextcharacters Usessequenceoperations e.g.:(),,`

grep

Usesallregularexpressions Onlyonethatallowssaving

Commands
Command b c i n s v x ffile Description Precedeseachlinebythefileblock# Printsonlyacountofthenumberof linesmatchingthepattern Ignoresupper/lowercasematching Showsthelinenumbers SilentMode(no output) Inverse Output(linesthatdontmatch) Printsonlylinesthatentirelymatch Listofstrings tobematchedareina file

Searching
y grepcansearchforfileswiththesamenameina

directory y Findcommandlocatesthepathofafile

Demo_file
y $catdemo_file
THISLINEISTHE1STUPPERCASELINEINTHISFILE. thislineisthe1stlowercaselineinthisfile. ThisLineHasAllItsFirstCharacterOfTheWordWithUpper Case. Twolinesabovethislineisempty. Andthisisthelastline.

Grepusage
y grep something

somefile.txtreturnsalllines withthewordsomethingfromsomefile.txt

y grep vsomethingsomething.txtreturnsalllines

thatdon'thavethewordsomethinginthem
y grep i somethingsomething.txtreturnsall

lineswithamixedupperandlowercase somethinginthem.

Advancedregularexpressions
y Linesthathavecatfollowedbydogonthesameline,but

possiblywithothercharactersinbetween: y grep 'cat.*dog'animalfarm.txt


y cathastobeatthebeginningoftheline:
y grep ^this'animalfarm.txt

y .

A=This is it echo $A | grep This

Displayinglinesbefore/after/aroundthematchusing grep A,BandC


y DisplayNlinesaftermatch
y AistheoptionwhichprintsthespecifiedNlinesafterthe

matchasshownbelow. y Syntax:grepA<N>"string"FILENAME

y Thefollowingexampleprintsthematchedline,along

withthe3linesafterit.
y $grep A3i "example"demo_file

y Linesthatdonotmatch
y grep vabove"demo_text

Countingthenumberofmatchesusinggrep c
y y y y

Syntax: grep c"pattern"filename $grep cthis"demo_file 6

Displayonlythefilenameswhichmatchesthegivenpatternusinggrep l
y

$grep lthisdemo_*
y y

demo_file demo_file1

Showthepositionofmatchintheline
y y

Syntax: grep ob"pattern"file $cattempfile.txt 12345 12345 $grep ob"3"tempfile.txt 2:3 8:3

y y y

y y y

Extended/EnhancedgrepwithmoreREmetacharacters
y treats+,?,|,(,and)asmetacharacters. y Inbasicregularexpressions(withgrep),themeta

egrep(grepE)

characters?,+,{,|,(,and)losetheirspecialmeaning.
y If youwantgrep totreatthesecharactersasmeta

characters,escapethem\?,\+,\{,\|,\(,and\)

y Characterswithspecialmeaningtotheshell($,*,[,|,

^,(,),\ )mustbeinquotationmarkswhenthey appearinthePattern parameter. y WhenthePattern parameterisnotasimplestring, youusuallymustenclosetheentirepatterninsingle quotationmarks.

Extended/EnhancedgrepwithmoreREmetacharacters

egrep(grepE)

100ThomasManagerSales$5,000 200JasonDeveloperTechnology$5,500 300SanjaySysadmin Technology$7,000 400Nisha ManagerMarketing$9,500 500RandyDBATechnology$6,000

Uses
y SearchforSpecificCharacters y ThefollowingexamplesearchesforeitherJ,orN,orR.
$egrep [JNR]employee.txt 200JasonDeveloperTechnology$5,500 400Nisha ManagerMarketing$9,500 500RandyDBATechnology$6,000

SearchforaRange
y Thefollowingexamplesearchestherange69.i.e

Itsearchesfor6,or7,or8,or9.
$egrep [69]employee.txt 300SanjaySysadmin Technology$7,000 400Nisha ManagerMarketing$9,500 500RandyDBATechnology$6,000

egrep ORExample
y Pipesymbolisusedforegrep OR.Thefollowing

searchesforeitherMarketingorDBA

$egrep 'Marketing|DBA'employee.txt 400Nisha ManagerMarketing$9,500 500RandyDBATechnology$6,000

y countthenumberoflinesinemployee.txtwhich

eitherstartwith3orendwith500
egrep c^3|500$'employee.txt 200JasonDeveloperTechnology$5,500 300SanjaySysadmin Technology$7,000 400Nisha ManagerMarketing$9,500

sed
y Sed istheultimatestreameditor y sedcanbeusedtofiltertextfiles.Thepatterntomatchistypically

includedbetweenapairofslashes//andquoted. y ForEXAMPLE,toprintlinescontainingthestring"1024",youmay use: y catfilename|sedn'/1024/p y Here,sedfilterstheoutputfromthecatcommand.Theoption"n"tells sedtoblockalltheincominglinesbutthoseexplicitlymatchingthe expression.Thesedactiononamatchis"p"=print. y Thecharacterafterthes isthedelimiter.Itisconventionallyaslash, becausethisiswhated,more,andvi use.Itcanbeanythingyouwant, however.Ifyouwanttochangeapathnamethatcontainsaslash say /usr/local/binto/common/bin youcouldusethebackslashtoquote theslash: y sed's/\/usr\/local\/bin/\/common\/bin/'<old>new

y Acommonuseofsedistomodifyeachlineofafileor

streambyreplacingspecifiedpartsoftheline.For exampleifyouhaveafilethatcontainsthelines: 1,JustinTimberlake,Title545,Price$6.30 2,TaylorSwift,Title723,Price$7.90 3,MickJagger,Title610,Price$7.90 4,LadyGaga,Title118,Price$6.30 5,JohnnyCash,Title482,Price$6.50 6,ElvisPresley,Title335,Price$6.30 7,JohnLennon,Title271,Price$7.90

Changeoccurances
y changealloccurrencesof6.30to7.30youcouldusethe

command:

y sed's/6.30/7.30/'songs.txt>songs2.txt

1,JustinTimberlake,Title545,Price$7.30 2,TaylorSwift,Title723,Price$7.90 3,MickJagger,Title610,Price$7.90 4,LadyGaga,Title118,Price$7.30 5,JohnnyCash,Title482,Price$6.50 6,ElvisPresley,Title335,Price$7.30 7,JohnLennon,Title271,Price$7.90

Filteringlines
y Sedisalsofrequentlyusedtofilterlinesinafileor

stream.Forexampleifyouonlywantseethelines containing"John"youcoulduse:
y sedn'/John/p'songs.txt>johns.txt

5,JohnnyTrash,Title482,Price$6.50 7,JohnLennon,Title271,Price$7.90

y echoSunday|sed's/day/light/' y Therearefourpartstothissubstitutecommand:
y s

Substitutecommand y /../../ Delimiter y day RegularExpressionPatternSearchPattern y Night Replacementstring

y Thiswouldoutputtheword"Sunlight"becausesed

foundthestring"day"intheinput.

Parenthesizefirstcharacterofeachword

y Thissedexampleprintsthefirstcharacterofevery

wordinparenthesis.
$echo"WelcomeToTheGeekStuff3aaa"|sed's/\(\b[A Z]\)/\(\1\)/g' (W)elcome (T)o(T)he(G)eek(S)tuff

Commify thesimplenumber
$catnumbers 1234 12121 3434 123 $sed's/\(^\|[^09.]\)\([09]\+\)\([09]\{3\}\)/\1\2,\3/g'numbers 1,234 12,121 3,434 123

By:Yogesh Chaudhari

S-ar putea să vă placă și