Tải bản đầy đủ - 0 (trang)
Chapter 5. The awk Utility: awk as a UNIX Tool

Chapter 5. The awk Utility: awk as a UNIX Tool

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

Chapter5.TheawkUtility:awkasaUNIX

Tool

5.1WhatIsawk?

5.2awk'sFormat

5.3FormattingOutput

5.4awkCommandsfromWithinaFile

5.5RecordsandFields

5.6PatternsandActions

5.7RegularExpressions

5.8awkCommandsinaScriptFile

5.9Review

UNIXTOOLSLABEXERCISE



5.1WhatIsawk?



Awkisaprogramminglanguageusedformanipulatingdataand

generatingreports.Thedatamaycomefromstandardinput,oneormore

files,orasoutputfromaprocess.Awkcanbeusedatthecommandline

forsimpleoperations,oritcanbewrittenintoprogramsforlarger

applications.Becauseawkcanmanipulatedata,itisanindispensable

toolusedinshellscriptsandformanagingsmalldatabases.

Awkscansafile(orinput)linebyline,fromthefirsttothelastline,

searchingforlinesthatmatchaspecifiedpatternandperformingselected

actions(enclosedincurlybraces)onthoselines.Ifthereisapatternwith

nospecificaction,alllinesthatmatchthepatternaredisplayed;ifthereis

anactionwithnopattern,allinputlinesspecifiedbytheactionare

executedupon.



5.1.1WhatDoesawkStandfor?

Awkstandsforthefirstinitialsinthelastnamesofeachoftheauthorsof

thelanguage,AlfredAho,BrianKernighan,andPeterWeinberger.They

couldhavecalleditwakorkaw,butforwhateverreason,awkwonout.



5.1.2Whichawk?

Thereareanumberofversionsofawk:oldawk,newawk,gnuawk

(gawk),POSIXawk,andothers.Awkwasoriginallywrittenin1977,and

in1985,theoriginalimplementationwasimprovedsothatawkcould

handlelargerprograms.Additionalfeaturesincludeduser-defined

functions,dynamicregularexpressions,processingmultipleinputfiles,

andmore.Onmostsystems,thecommandisawkifusingtheold

version,nawkifusingthenewversion,andgawkifusingthegnuversion.

[1]



5.2awk'sFormat

Anawkprogramconsistsoftheawkcommand,theprograminstructions

enclosedinquotes(orinafile),andthenameoftheinputfile.Ifaninput

fileisnotspecified,inputcomesfromstandardinput(stdin),the



keyboard.

Awkinstructionsconsistofpatterns,actions,oracombinationofpatterns

andactions.Apatternisastatementconsistingofanexpressionofsome

type.Ifyoudonotseethekeywordif,butyouthinkthewordifwhen

evaluatingtheexpression,itisapattern.Actionsconsistofoneormore

statementsseparatedbysemicolonsornewlinesandenclosedincurly

braces.Patternscannotbeenclosedincurlybraces,andconsistof

regularexpressionsenclosedinforwardslashesorexpressions

consistingofoneormoreofthemanyoperatorsprovidedbyawk.

Awkcommandscanbetypedatthecommandlineorinawkscriptfiles.

Theinputlinescancomefromfiles,pipes,orstandardinput.



5.2.1InputfromFiles

Inthefollowingexamples,thepercentsign(%)istheCshellprompt.



FORMAT

%nawk'pattern'filename

%nawk'{action}'filename

%nawk'pattern{action}'filename

Hereisasamplefilecalledemployees:

Example5.1



%catemployees

TomJones44245/12/66543354

MaryAdams534611/4/6328765

SallyChang16547/22/54650000

BillyBlack16839/23/44336500

%nawk'/Mary/'employees

MaryAdams534611/4/6328765



EXPLANATION

NawkprintsalllinesthatcontainthepatternMary.



Example5.2



%catemployees

TomJones44245/12/66543354

MaryAdams534611/4/6328765

SallyChang16547/22/54650000

BillyBlack16839/23/44336500

%nawk'{print$1}'employees

Tom

Mary

Sally

Billy



EXPLANATION

Nawkprintsthefirstfieldoffileemployees,wherethefieldstarts

attheleftmarginofthelineandisdelimitedbywhitespace.



Example5.3



%catemployees

TomJones44245/12/66543354

MaryAdams534611/4/6328765

SallyChang16547/22/54650000

BillyBlack16839/23/44336500

%nawk'/Sally/{print$1,$2}'employees

SallyChang



EXPLANATION

Nawkprintsthefirstandsecondfieldsoffileemployees,onlyif

thelinecontainsthepatternSally.Remember,thefieldseparator

iswhitespace.



5.2.2InputfromCommands

TheoutputfromaUNIXcommandorcommandscanbepipedtoawkfor

processing.Shellprogramscommonlyuseawkformanipulating

commands.



FORMAT

%command|nawk'pattern'

%command|nawk'{action}'

%command|nawk'pattern{action}'



Example5.4



1%df|nawk'$4>75000'

/oracle(/dev/dsk/c0t0d057):390780blocks1

/opt(/dev/dsk/c0t0d058):1943994blocks

2%rusers|nawk'/root$/{print$1}'

owl

crow

bluebird



EXPLANATION

1.



Thedfcommandreportsthefreediskspaceonfile

systems.Theoutputofthedfcommandispipedto

nawk(newawk).Ifthefourthfieldisgreaterthan75,000

blocks,thelineisprinted.



Theruserscommandprintsthoseloggedonremotemachines

onthenetwork.Theoutputoftheruserscommandispipedto

nawkasinput.Thefirstfieldisprintediftheregularexpression

rootismatchedattheendoftheline($);thatis,allmachine

namesareprintedwhererootisloggedon.



5.3FormattingOutput

5.3.1TheprintFunction

Theactionpartoftheawkcommandisenclosedincurlybraces.Ifno

actionisspecifiedandapatternismatched,awktakesthedefaultaction,

whichistoprintthelinesthatarematchedtothescreen.Theprint

functionisusedtoprintsimpleoutputthatdoesnotrequirefancy

formatting.Formoresophisticatedformatting,theprintforsprintf

functionsareused.IfyouarefamiliarwithC,thenyoualreadyknowhow

printfandsprintfwork.

Theprintfunctioncanalsobeexplicitlyusedintheactionpartofawkas

{print}.Theprintfunctionacceptsargumentsasvariables,computed

values,orstringconstants.Stringsmustbeenclosedindoublequotes.

Commasareusedtoseparatethearguments;ifcommasarenot

provided,theargumentsareconcatenatedtogether.Thecomma

evaluatestothevalueoftheoutputfieldseparator(OFS),whichisby

defaultaspace.



Theoutputoftheprintfunctioncanberedirectedorpipedtoanother

program,andtheoutputofanotherprogramcanbepipedtoawkfor

printing.(See"Redirection"onpage16and"Pipes"onpage19.)

Example5.5



%date

WedJul2822:23:16PDT2001

%date|nawk'{print"Month:"$2"\nYear:",$6}'

Month:Jul

Year:2001



EXPLANATION

TheoutputoftheUNIXdatecommandwillbepipedtonawk.

ThestringMonth:isprinted,followedbythesecondfield,the

stringcontainingthenewlinecharacter,\n,andYear:,followed

bythesixthfield($6).



EscapeSequences.Escapesequencesarerepresentedbyabackslash

andaletterornumber.Theycanbeusedinstringstorepresenttabs,

newlines,formfeeds,andsoforth(seeTable5.1).

Table5.1.printEscapeSequences

EscapeSequence

Meaning

Backspace.

\b

Formfeed.

\f

Newline.

\n

Carriagereturn.

\r

Tab.

\t

Octalvalue47,asinglequote.

\047

\c

crepresentsanyothercharacter,e.g.,\".

Example5.6



TomJones44245/12/66543354

MaryAdams534611/4/6328765

SallyChang16547/22/54650000

BillyBlack16839/23/44336500



%nawk'/Sally/{print"\t\tHaveaniceday,"$1,$2"\

Haveaniceday,SallyChang!



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

Chapter 5. The awk Utility: awk as a UNIX Tool

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

×