Tải bản đầy đủ - 0 (trang)
Chapter 4. sed, the Streamlined Editor

Chapter 4. sed, the Streamlined Editor

Tải bản đầy đủ - 0trang

Chapter4.sed,theStreamlinedEditor

4.1WhatIssed?

4.2HowDoessedWork?

4.3Addressing

4.4CommandsandOptions

4.5ErrorMessagesandExitStatus

4.6sedExamples

4.7sedScripting

UNIXTOOLSLABEXERCISE



4.1WhatIssed?

Sedisastreamlined,noninteractiveeditor.Itallowsyoutoperformthe

samekindofeditingtasksusedintheviandexeditors.Insteadof

workinginteractivelywiththeeditor,thesedprogramletsyoutypeyour

editingcommandsatthecommandline,namethefile,andthenseethe

outputoftheeditingcommandonthescreen.Thesededitoris

nondestructive.Itdoesnotchangeyourfileunlessyousavetheoutput



withshellredirection.Alllinesareprintedtothescreenbydefault.

Thesededitorisusefulinshellscripts,whereusinginteractiveeditors

suchasviorexwouldrequiretheuserofthescripttohavefamiliarity

withtheeditorandwouldexposetheusertomakingunwanted

modificationstotheopenfile.Youcanalsoputsedcommandsinafile

calledasedscript,ifyouneedtoperformmultipleeditsordonotlike

worryingaboutquotingthesedcommandsattheshellcommandline.[1]



4.2HowDoessedWork?

Thesededitorprocessesafile(orinput)onelineatatimeandsendsits

outputtothescreen.Itscommandsarethoseyoumayrecognizefrom

thevianded/exeditors.Sedstoresthelineitiscurrentlyprocessingina

temporarybuffercalledapatternspace.Oncesedisfinishedprocessing

thelineinthepatternspace(i.e.,executingsedcommandsonthatline),

thelineinthepatternspaceissenttothescreen(unlessthecommand

wastodeletethelineorsuppressitsprinting).Afterthelinehasbeen

processed,itisremovedfromthepatternspaceandthenextlineisthen

readintothepatternspace,processed,anddisplayed.Sedendswhen

thelastlineoftheinputfilehasbeenprocessed.Bystoringeachlineina

temporarybufferandperformingeditsonthatline,theoriginalfileis

neveralteredordestroyed.



4.3Addressing

Youcanuseaddressingtodecidewhichlinesyouwanttoedit.The

addressescanbeintheformofnumbersorregularexpressions,ora

combinationofboth.Withoutspecifyinganaddress,sedprocessesall

linesoftheinputfile.

Whenanaddressconsistsofanumber,thenumberrepresentsaline

number.Adollarsigncanbeusedtorepresentthelastlineoftheinput

file.Ifacommaseparatestwolinenumbers,theaddressesthatwillbe

processedarewithinthatrangeoflines,includingthefirstandlastlinein

therange.Therangemaybenumbers,regularexpressions,ora



combinationofnumbersandregularexpressions.

Sedcommandstellsedwhattodowiththeline:printit,removeit,

changeit,andsoforth.



FORMAT

sed'command'filename(s)



Example4.1



1%sed'1,3p'myfile

2%sed-n'/[Jj]ohn/p'datafile



EXPLANATION

1.



Lines1through3ofmyfileareprinted.

OnlylinesmatchingthepatternJohnorjohninmyfileare

printed.



4.4CommandsandOptions

Sedcommandstellsedhowtoprocesseachlineofinputspecifiedbyan

address.Ifanaddressisnotgiven,sedprocesseseverylineofinput.

(The%isthecshprompt.)SeeTable4.1foralistofsedcommandsand

whattheydo,andseeTable4.2foralistofoptionsandhowtheycontrol

sed'sbehavior.

Example4.2



%sed'1,3d'file



EXPLANATION

Sedwilldeletelines1through3.



Table4.1.sedCommands

Command

Function

Appendsoneormorelinesoftexttothecurrentline.

a\

Changes(replaces)textinthecurrentlinewithnewtext.

c\

Deleteslines.

d

Insertstextabovethecurrentline.

i\

Copiesthecontentsofthepatternspacetoaholdingbuffer.

h

Appendsthecontentsofthepatternspacetoaholding

H

buffer.

Getswhatisintheholdingbufferandcopiesitintothe

g

patternbuffer,overwritingwhatwasthere.

Getswhatisintheholdingbufferandcopiesitintothe

G

patternbuffer,appendingtowhatwasthere.

Listsnonprintingcharacters.

l

Printslines.

p

Readsthenextinputlineandstartsprocessingthenewline

n

withthenextcommandratherthanthefirstcommand.

Quitsorexitssed.

q

Readslinesfromafile.

r

Appliesthecommandtoalllinesexcepttheselectedones.

!

Substitutesonestringforanother.

s

SubstitutionFlags:

Globallysubstitutesonaline.

g

Printslines.

p



w

x

y



Writeslinesouttoafile.

Exchangescontentsoftheholdingbufferwiththepattern

space.

Translatesonecharactertoanother(cannotuseregular

expressionmetacharacterswithy).







Options

-e

-f

-n



Table4.2.sedOptions

Function

Allowsmultipleedits.

Precedesasedscriptfilename.

Suppressesdefaultoutput.



Whenmultiplecommandsareusedoraddressesneedtobenested

withinarangeofaddresses,thecommandsareenclosedincurlybraces

andeachcommandiseitheronaseparatelineorterminatedwith

semicolons.

Theexclamationpoint(!)canbeusedtonegateacommand.For

example,



%sed'/Tom/d'file

tellssedtodeletealllinescontainingthepatternTom,whereas



%sed'/Tom/!d'file

tellssedtodeletelinesnotcontainingTom.

Thesedoptionsare-e,-f,and,-n.The-eisusedformultipleeditsatthe

commandline,the-fprecedesasedscriptfilename,andthe-n

suppressesprintingoutput.



4.5ErrorMessagesandExitStatus



Whensedencountersasyntaxerror,itsendsaprettystraightforward

errormessagetostandarderror,butifitcannotfigureoutwhatyoudid

wrong,sedgets"garbled,"whichwecouldguessmeansconfused.The

exitstatusthatsedreturnstotheshell,ifitssyntaxiserror-free,isazero

forsuccessandanonzerointegerforfailure.[2]

Example4.3



1%sed'1,3v'file

sed:Unrecognizedcommand:1,3v

%echo$status(echo$?ifusingKornorBournesh

2

2%sed'/^John'file

sed:Illegalormissingdelimiter:/^John



3%sed's/134345/g'file

sed:Endingdelimitermissingonsubstitution:s/13



EXPLANATION

1. Thevcommandisunrecognizedbysed.Theexitstatus

was2,indicatingthatsedexitedwithasyntaxproblem.

Thepattern/^Johnismissingtheclosingforwardslash.

Thesubstitutioncommand,s,containsthesearchstringbut

notthereplacementstring.



4.5.1Metacharacters

Likegrep,sedsupportsanumberofspecialmetacharacterstocontrol

patternsearching.SeeTable4.3

Table4.3.sed'sRegularExpressionMetacharacters.

Metacharacter Function

Example

WhatItMatches

Beginning- /^love/

Matchesalllines

^

of-line

beginningwithlove.

anchor

End-of-line /love$/

Matchesalllinesending

$

anchor

withlove.

Matches

Matcheslinescontaining

.

/l..e/

one

anl,followedbytwo

character,

characters,followedbyan

butnotthe

e.

newline

character

Matches

Matcheslineswithzeroor

*

/*love/

zeroormore

morespaces,followedby

characters

thepatternlove.

Matches

Matcheslinescontaining

[]

/[Ll]ove/

one

loveorLove.



[^]



\(..\)



&



\<



\>



x\{m\}



characterin

theset

Matches

/[^A-KM-Z]ove/ Matcheslinesnot

one

containingAthroughKor

character

MthroughZfollowedby

notinthe

ove.

set

Saves

Tagsmarkedportionand

s/\

matched

(love\)able/\1er/ savesitastagnumber1.

characters

Toreferencelater,use\1

toreferencethepattern.

Mayuseuptoninetags,

startingwiththefirsttag

attheleftmostpartofthe

pattern.Forexample,love

issavedinregister1and

rememberedinthe

replacementstring.

lovableisreplacedwith

lover.

Saves

Theampersand

s/love/**&**/

search

representsthesearch

stringsoit

string.Thestringlovewill

canbe

bereplacedwithitself

remembered

surroundedbyasterisks;

inthe

i.e.,lovewillbecome

replacement

**love**.

string

Beginning- /\
Matcheslinescontaining

of-word

awordthatbeginswith

anchor

love.

End-of-word /love\>/

Matcheslinescontaining

anchor

awordthatendswith

love.

Matchesiflinehas5

/o\{5\}/

Repetitionof

occurrencesofo,atleast

characterx:

5occurrencesofo,or



x\{m,\}



mtimes



x\{m,n\}[a]



atleastm

times



between5and10

occurrencesofo.



atleastm

andnot

morethann

times



[a]NotdependableonallversionsofUNIXorallpattern-matchingutilities;usuallyworks



withviandgrep.



4.6sedExamples



%catdatafile

northwestNWCharlesMain3.0.98

westernWESharonGray5.3.97

southwestSWLewisDalsass2.7.8

southernSOSuanChin5.1.95

southeastSEPatriciaHemenway4.0.7

easternEATBSavage4.4.84

northeastNEAMMainJr.5.1.94

northNOMargotWeber4.5.89

centralCTAnnStephens5.7.94

4.6.1Printing:ThepCommand

Example4.4



sed'/north/p'datafile

northwestNWCharlesMain3.0.983

northwestNWCharlesMain3.0.983



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. sed, the Streamlined Editor

Tải bản đầy đủ ngay(0 tr)

×