AdvancedEditingonUNIX BrianW.Kernighan ABSTRACT Thispaperismeanttohelpsecretaries,typistsandprogrammerstomake effectiveuseoftheUNIX◯rfacilitiesforpreparingandeditingtext.Itprovides explanationsandexamplesof •specialcharacters,lineaddressingandglobalcommandsintheeditored; •commandsfor‘‘cutandpaste’’operationsonfilesandpartsoffiles,includingthemv,cp,catandrmcommands,andther,w,mandtcommands oftheeditor; •editingscriptsandeditor-basedprogramslikegrepandsed. Althoughthetreatmentisaimedatnon-programmers,newuserswithany backgroundshouldfindhelpfulhintsonhowtogettheirjobsdonemoreeasily. 6April1993 AdvancedEditingonUNIX BrianW.Kernighan 1.INTRODUCTION AlthoughUNIXprovidesremarkablyeffective toolsfortextediting,thatbyitselfisnoguarantee thateveryonewillautomaticallymakethemost effectiveuseofthem.Inparticular,peoplewho arenotcomputerspecialists—typists,secretaries, casualusers—oftenusethesystemlesseffectively thantheymight. ThisdocumentisintendedasasequeltoA TutorialIntroductiontotheUNIXTextEditor[1], providingexplanationsandexamplesofhowto editwithlesseffort.(Youshouldalsobefamiliar withthematerialinUNIXForBeginners[2].) Furtherinformationonallcommandsdiscussed herecanbefoundinTheUNIXProgrammer’s Manual[3]. Examplesarebasedonobservationsofusers andthedifficultiestheyencounter.Topicscovered includespecialcharactersinsearchesandsubstitutecommands,lineaddressing,theglobalcommands,andlinemovingandcopying.Thereare alsobriefdiscussionsofeffectiveuseofrelated tools,likethoseforfilemanipulation,andthose basedoned,likegrepandsed. Awordofcaution.Thereisonlyoneway tolearntousesomething,andthatistouseit. Readingadescriptionisnosubstitutefortrying something.Apaperlikethisoneshouldgiveyou ideasaboutwhattotry,butuntilyouactuallytry something,youwillnotlearnit. 2.SPECIALCHARACTERS Theeditoredistheprimaryinterfacetothe systemformanypeople,soitisworthwhileto knowhowtogetthemostoutofedfortheleast effort. Thenextfewsectionswilldiscussshortcuts andlabor-savingdevices.Notallofthesewillbe instantlyusefultoanyoneperson,ofcourse,buta fewwillbe,andtheothersshouldgiveyouideas tostoreawayforfutureuse.Andasalways,until youtrythesethings,theywillremaintheoretical knowledge,notsomethingyouhaveconfidencein. TheListcommand‘l’ edprovidestwocommandsforprintingthe contentsofthelinesyou’reediting.Mostpeople arefamiliarwithp,incombinationslike 1,$p toprintallthelinesyou’reediting,or s/abc/def/p tochange‘abc’to‘def’onthecurrentline.Less familiaristhelistcommandl(theletter‘l’), whichgivesslightlymoreinformationthanp.In particular,lmakesvisiblecharactersthatarenormallyinvisible,suchastabsandbackspaces.If youlistalinethatcontainssomeofthese,lwill printeachtabas−>andeachbackspaceas−<. Thismakesitmucheasiertocorrectthesortof typingmistakethatinsertsextraspacesadjacent totabs,orinsertsabackspacefollowedbyaspace. Thelcommandalso‘folds’longlinesfor printing—anylinethatexceeds72charactersis printedonmultiplelines;eachprintedlineexcept thelastisterminatedbyabackslash\\,soyoucan tellitwasfolded.Thisisusefulforprintinglong linesonshortterminals. Occasionallythelcommandwillprintina lineastringofnumbersprecededbyabackslash, suchas\\07or\\16.Thesecombinationsareused tomakevisiblecharactersthatnormallydon’t print,likeformfeedorverticaltaborbell.Each suchcombinationisasinglecharacter.Whenyou seesuchcharacters,bewary—theymayhavesurprisingmeaningswhenprintedonsometerminals. Oftentheirpresencemeansthatyourfinger slippedwhileyouweretyping;youalmostnever wantthem. TheSubstituteCommand‘s’ Mostofthenextfewsectionswillbetaken upwithadiscussionofthesubstitutecommands. Sincethisisthecommandforchangingthecontentsofindividuallines,itprobablyhasthemost complexityofanyedcommand,andthemost potentialforeffectiveuse. Asthesimplestplacetobegin,recallthe meaningofatrailinggafterasubstitutecommand.With s/this/that/ and s/this/that/g thefirstonereplacesthefirst‘this’ontheline with‘that’.Ifthereismorethanone‘this’onthe -2-line,thesecondformwiththetrailinggchanges allofthem. Eitherformofthescommandcanbefollowedbyporlto‘print’or‘list’(asdescribedin theprevioussection)thecontentsoftheline: s/this/that/p s/this/that/l s/this/that/gp s/this/that/gl arealllegal,andmeanslightlydifferentthings. Makesureyouknowwhatthedifferencesare. Ofcourse,anyscommandcanbepreceded byoneortwo‘linenumbers’tospecifythatthe substitutionistotakeplaceonagroupoflines. Thus 1,$s/mispell/misspell/ changesthefirstoccurrenceof‘mispell’to‘misspell’oneverylineofthefile.But 1,$s/mispell/misspell/g changeseveryoccurrenceineveryline(andthisis morelikelytobewhatyouwantedinthisparticularcase). Youshouldalsonoticethatifyouaddap orltotheendofanyofthesesubstitutecommands,onlythelastlinethatgotchangedwillbe printed,notallthelines.Wewilltalklaterabout howtoprintallthelinesthatweremodified. TheUndoCommand‘u’ Occasionallyyouwillmakeasubstitutionin aline,onlytorealizetoolatethatitwasaghastly mistake.The‘undo’commanduletsyou‘undo’ thelastsubstitution:thelastlinethatwassubstitutedcanberestoredtoitspreviousstatebytypingthecommand u TheMetacharacter‘.’ Asyouhaveundoubtedlynoticedwhenyou useed,certaincharactershaveunexpectedmeaningswhentheyoccurintheleftsideofasubstitutecommand,orinasearchforaparticularline. Inthenextseveralsections,wewilltalkabout thesespecialcharacters,whichareoftencalled ‘metacharacters’. Thefirstoneistheperiod‘.’.Ontheleft sideofasubstitutecommand,orinasearchwith ‘/.../’,‘.’standsforanysinglecharacter.Thus thesearch /x.y/ findsanylinewhere‘x’and‘y’occurseparatedby asinglecharacter,asin x+y x−y xy x.y andsoon.(Wewillusetostandforaspace wheneverweneedtomakeitvisible.) Since‘.’matchesasinglecharacter,that givesyouawaytodealwithfunnycharacters printedbyl.Supposeyouhavealinethat,when printedwiththelcommand,appearsas ....th\\07is.... andyouwanttogetridofthe\\07(whichrepresentsthebellcharacter,bytheway). Themostobvioussolutionistotry s/\\07// butthiswillfail.(Tryit.)Thebruteforcesolution,whichmostpeoplewouldnowtake,istoretypetheentireline.Thisisguaranteed,andis actuallyquiteareasonabletacticifthelinein questionisn’ttoobig,butforaverylongline,retypingisabore.Thisiswherethemetacharacter ‘.’comesinhandy.Since‘\\07’reallyrepresentsa singlecharacter,ifwesay s/th.is/this/ thejobisdone.The‘.’matchesthemysterious characterbetweenthe‘h’andthe‘i’,whateverit is. Bearinmindthatsince‘.’matchesanysinglecharacter,thecommand s/./,/ convertsthefirstcharacteronalineintoa‘,’, whichveryoftenisnotwhatyouintended. Asistrueofmanycharactersined,the‘.’ hasseveralmeanings,dependingonitscontext. Thislineshowsallthree: .s/././ Thefirst‘.’isalinenumber,thenumberofthe lineweareediting,whichiscalled‘linedot’.(We willdiscusslinedotmoreinSection3.)Thesecond‘.’isametacharacterthatmatchesanysingle characteronthatline.Thethird‘.’istheonly onethatreallyisanhonestliteralperiod.Onthe rightsideofasubstitution,‘.’isnotspecial.If youapplythiscommandtotheline Nowisthetime. theresultwillbe .owisthetime. whichisprobablynotwhatyouintended.

-3-TheBackslash‘\\’ Sinceaperiodmeans‘anycharacter’,the questionnaturallyarisesofwhattodowhenyou reallywantaperiod.Forexample,howdoyou converttheline Nowisthetime. into Nowisthetime? Thebackslash‘\\’doesthejob.Abackslashturns offanyspecialmeaningthatthenextcharacter mighthave;inparticular,‘\\.’convertsthe‘.’from a‘matchanything’intoaperiod,soyoucanuseit toreplacetheperiodin Nowisthetime. likethis: s/\\./?/ Thepairofcharacters‘\\.’isconsideredbyedto beasinglerealperiod. Thebackslashcanalsobeusedwhensearchingforlinesthatcontainaspecialcharacter.Supposeyouarelookingforalinethatcontains .PP Thesearch /.PP/ isn’tadequate,foritwillfindalinelike THEAPPLICATIONOF... becausethe‘.’matchestheletter‘A’.Butifyou say /\\.PP/ youwillfindonlylinesthatcontain‘.PP’. Thebackslashcanalsobeusedtoturnoff specialmeaningsforcharactersotherthan‘.’.For example,considerfindingalinethatcontainsa backslash.Thesearch /\\/ won’twork,becausethe‘\\’isn’taliteral‘\\’,but insteadmeansthatthesecond‘/’nolonger delimitsthesearch.Butbyprecedingabackslash withanotherone,youcansearchforaliteralbackslash.Thus /\\\\/ doeswork.Similarly,youcansearchforaforward slash‘/’with /\\// Thebackslashturnsoffthemeaningoftheimmediatelyfollowing‘/’sothatitdoesn’tterminate the/.../constructionprematurely. Asanexercise,beforereadingfurther,find twosubstitutecommandseachofwhichwillconverttheline \\x\\.\\y intotheline \\x\\y Hereareseveralsolutions;verifythateach worksasadvertised. s/\\\\\\.// s/x../x/ s/..y/y/ Acoupleofmiscellaneousnotesaboutbackslashesandspecialcharacters.First,youcanuse anycharactertodelimitthepiecesofanscommand:thereisnothingsacredaboutslashes.(But youmustuseslashesforcontextsearching.)For instance,inalinethatcontainsalotofslashes already,like //exec//sys.fort.go//etc... youcoulduseacolonasthedelimiter—todelete alltheslashes,type s:/::g Second,if#and@areyourcharactererase andlinekillcharacters,youhavetotype\\#and \\@;thisistruewhetheryou’retalkingtoedor anyotherprogram. Whenyouareaddingtextwithaoriorc, backslashisnotspecial,andyoushouldonlyput inonebackslashforeachoneyoureallywant. TheDollarSign‘$’ Thenextmetacharacter,the‘$’,standsfor ‘theendoftheline’.Asitsmostobvioususe,supposeyouhavetheline Nowisthe andyouwishtoaddtheword‘time’totheend. Usethe$likethis: s/$/time/ toget Nowisthetime Noticethataspaceisneededbefore‘time’inthe substitutecommand,oryouwillget Nowisthetime Asanotherexample,replacethesecond commainthefollowinglinewithaperiodwithout alteringthefirst:

-4-Nowisthetime,forallgoodmen, Thecommandneededis s/,$/./ The$signhereprovidescontexttomakespecific whichcommawemean.Withoutit,ofcourse,the scommandwouldoperateonthefirstcommato produce Nowisthetime.forallgoodmen, Asanotherexample,toconvert Nowisthetime. into Nowisthetime? aswedidearlier,wecanuse s/.$/?/ Like‘.’,the‘$’hasmultiplemeanings dependingoncontext.Intheline $s/$/$/ thefirst‘$’referstothelastlineofthefile,the secondreferstotheendofthatline,andthethird isaliteraldollarsign,tobeaddedtothatline. TheCircumflex‘ˆ ’ Thecircumflex(orhatorcaret)‘ˆ ’stands forthebeginningoftheline.Forexample,supposeyouarelookingforalinethatbeginswith ‘the’.Ifyousimplysay /the/ youwillinalllikelihoodfindseverallinesthatcontain‘the’inthemiddlebeforearrivingattheone youwant.Butwith /ˆ the/ younarrowthecontext,andthusarriveatthe desiredonemoreeasily. Theotheruseof‘ˆ ’isofcoursetoenable youtoinsertsomethingatthebeginningofaline: s/ˆ // placesaspaceatthebeginningofthecurrentline. Metacharacterscanbecombined.Tosearch foralinethatcontainsonlythecharacters .PP youcanusethecommand /ˆ \\.PP$/ TheStar‘∗’ Supposeyouhavealinethatlookslikethis: textxytext wheretextstandsforlotsoftext,andthereare someindeterminatenumberofspacesbetweenthe xandthey.Supposethejobistoreplaceallthe spacesbetweenxandybyasinglespace.The lineistoolongtoretype,andtherearetoomany spacestocount.Whatnow? Thisiswherethemetacharacter‘∗’comesin handy.Acharacterfollowedbyastarstandsfor asmanyconsecutiveoccurrencesofthatcharacter aspossible.Torefertoallthespacesatonce,say s/x∗y/xy/ Theconstruction‘∗’means‘asmanyspacesas possible’.Thus‘x∗y’means‘anx,asmany spacesaspossible,thenay’. Thestarcanbeusedwithanycharacter, notjustspace.Iftheoriginalexamplewasinstead textx−−−−−−−−ytext thenall‘−’signscanbereplacedbyasinglespace withthecommand s/x−∗y/xy/ Finally,supposethatthelinewas textx..................ytext Canyouseewhattrapliesinwaitfortheunwary? Ifyoublindlytype s/x.∗y/xy/ whatwillhappen?Theanswer,naturally,isthat itdepends.Iftherearenootherx’sory’sonthe line,theneverythingworks,butit’sblindluck,not goodmanagement.Rememberthat‘.’matches anysinglecharacter?Then‘.∗’matchesasmany singlecharactersaspossible,andunlessyou’re careful,itcaneatupalotmoreofthelinethan youexpected.Ifthelinewas,forexample,like this: textxtextx................ytextytext thensaying s/x.∗y/xy/ willtakeeverythingfromthefirst‘x’tothelast ‘y’,which,inthisexample,isundoubtedlymore thanyouwanted. Thesolution,ofcourse,istoturnoffthe specialmeaningof‘.’with‘\\.’: s/x\\.∗y/xy/ Noweverythingworks,for‘\\.∗’means‘asmany periodsaspossible’.

-5-Therearetimeswhenthepattern‘.∗’is exactlywhatyouwant.Forexample,tochange Nowisthetimeforallgoodmen.... into Nowisthetime. use‘.∗’toeatupeverythingafterthe‘for’: s/for.∗/./ Thereareacoupleofadditionalpitfalls associatedwith‘∗’thatyoushouldbeawareof. Mostnotableisthefactthat‘asmanyaspossible’ meanszeroormore.Thefactthatzeroisalegitimatepossibilityissometimesrathersurprising. Forexample,ifourlinecontained textxytextxytext andwesaid s/x∗y/xy/ thefirst‘xy’matchesthispattern,foritconsistsof an‘x’,zerospaces,anda‘y’.Theresultisthat thesubstituteactsonthefirst‘xy’,anddoesnot touchthelateronethatactuallycontainssome interveningspaces. Thewayaroundthis,ifitmatters,isto specifyapatternlike /x∗y/ whichsays‘anx,aspace,thenasmanymore spacesaspossible,thenay’,inotherwords,one ormorespaces. Theotherstartlingbehaviorof‘∗’isagain relatedtothefactthatzeroisalegitimatenumber ofoccurrencesofsomethingfollowedbyastar. Thecommand s/x∗/y/g whenappliedtotheline abcdef produces yaybycydyeyfy whichisalmostcertainlynotwhatwasintended. Thereasonforthisbehavioristhatzeroisalegal numberofmatches,andtherearenox’satthe beginningoftheline(sothatgetsconvertedintoa ‘y’),norbetweenthe‘a’andthe‘b’(sothatgets convertedintoa‘y’),nor...andsoon.Makesure youreallywantzeromatches;ifnot,inthiscase write s/xx∗/y/g ‘xx∗’isoneormorex’s.

TheBrackets‘[]’ Supposethatyouwanttodeleteanynumbersthatappearatthebeginningofalllinesofa file.Youmightfirstthinkoftryingaseriesof commandslike 1,$s/ˆ 1∗// 1,$s/ˆ 2∗// 1,$s/ˆ 3∗// andsoon,butthisisclearlygoingtotakeforever ifthenumbersareatalllong.Unlessyouwantto repeatthecommandsoverandoveruntilfinallyall numbersaregone,youmustgetallthedigitson onepass.Thisisthepurposeofthebrackets[and ]. Theconstruction [0123456789] matchesanysingledigit—thewholethingis calleda‘characterclass’.Withacharacterclass, thejobiseasy.Thepattern‘[0123456789]∗’ matcheszeroormoredigits(anentirenumber),so 1,$s/ˆ [0123456789]∗// deletesalldigitsfromthebeginningofalllines. Anycharacterscanappearwithinacharacterclass,andjusttoconfusetheissuethereare essentiallynospecialcharactersinsidethebrackets;eventhebackslashdoesn’thaveaspecial meaning.Tosearchforspecialcharacters,for example,youcansay /[.\\$ˆ []/ Within[...],the‘[’isnotspecial.Togeta‘]’into acharacterclass,makeitthefirstcharacter. It’sanuisancetohavetospelloutthedigits,soyoucanabbreviatethemas[0−9];similarly, [a−z]standsforthelowercaseletters,and[A−Z] foruppercase. Asafinalfrilloncharacterclasses,youcan specifyaclassthatmeans‘noneofthefollowing characters’.Thisisdonebybeginningtheclass witha‘ˆ ’: [ˆ 0−9] standsfor‘anycharacterexceptadigit’.Thusyou mightfindthefirstlinethatdoesn’tbeginwitha taborspacebyasearchlike /ˆ [ˆ (space)(tab)]/ Withinacharacterclass,thecircumflexhas aspecialmeaningonlyifitoccursatthebeginning.Justtoconvinceyourself,verifythat /ˆ [ˆ ˆ ]/ findsalinethatdoesn’tbeginwithacircumflex.

-6-TheAmpersand‘&’ Theampersand‘&’isusedprimarilytosave typing.Supposeyouhavetheline Nowisthetime andyouwanttomakeit Nowisthebesttime Ofcourseyoucanalwayssay s/the/thebest/ butitseemssillytohavetorepeatthe‘the’.The ‘&’isusedtoeliminatetherepetition.Onthe rightsideofasubstitute,theampersandmeans ‘whateverwasjustmatched’,soyoucansay s/the/&best/ andthe‘&’willstandfor‘the’.Ofcoursethis isn’tmuchofasavingifthethingmatchedisjust ‘the’,butifitissomethingtrulylongorawful,or ifitissomethinglike‘.∗’whichmatchesalotof text,youcansavesometedioustyping.Thereis alsomuchlesschanceofmakingatypingerrorin thereplacementtext.Forexample,toparenthesizealine,regardlessofitslength, s/.∗/(&)/ Theampersandcanoccurmorethanonce ontherightside: s/the/&bestand&worst/ makes Nowisthebestandtheworsttime and s/.∗/&?&!!/ convertstheoriginallineinto Nowisthetime?Nowisthetime!! Togetaliteralampersand,naturallythe backslashisusedtoturnoffthespecialmeaning: s/ampersand/\\&/ convertsthewordintothesymbol.Noticethat ‘&’isnotspecialontheleftsideofasubstitute, onlyontherightside. SubstitutingNewlines edprovidesafacilityforsplittingasingle lineintotwoormoreshorterlinesby‘substituting inanewline’.Asthesimplestexample,supposea linehasgottenunmanageablylongbecauseofediting(ormerelybecauseitwasunwiselytyped).If itlookslike textxytext youcanbreakitbetweenthe‘x’andthe‘y’like this: s/xy/x\\ y/ Thisisactuallyasinglecommand,althoughitis typedontwolines.Bearinginmindthat‘\\’turns offspecialmeanings,itseemsrelativelyintuitive thata‘\\’attheendofalinewouldmakethenewlinetherenolongerspecial. Youcaninfactmakeasinglelineintoseverallineswiththissamemechanism.Asalarge example,considerunderliningtheword‘very’ina longlinebysplitting‘very’ontoaseparateline, andprecedingitbytheroffornroffformatting command‘.ul’. textaverybigtext Thecommand s/very/\\ .ul\\ very\\ / convertsthelineintofourshorterlines,preceding theword‘very’bytheline‘.ul’,andeliminating thespacesaroundthe‘very’,allatthesametime. Whenanewlineissubstitutedin,dotisleft pointingatthelastlinecreated. JoiningLines Linesmayalsobejoinedtogether,butthis isdonewiththejcommandinsteadofs.Given thelines Nowis thetime andsupposingthatdotissettothefirstofthem, thenthecommand j joinsthemtogether.Noblanksareadded,which iswhywecarefullyshowedablankatthebeginningofthesecondline. Allbyitself,ajcommandjoinslinedotto linedot+1,butanycontiguoussetoflinescanbe joined.Justspecifythestartingandendingline numbers.Forexample, 1,$jp joinsallthelinesintoonebigoneandprintsit. (MoreonlinenumbersinSection3.) RearrangingaLinewith\\(...\\) (Thissectionshouldbeskippedonfirst reading.)Recallthat‘&’isashorthandthat standsforwhateverwasmatchedbytheleftside -7-ofanscommand.Inmuchthesamewayyoucan captureseparatepiecesofwhatwasmatched;the onlydifferenceisthatyouhavetospecifyonthe leftsidejustwhatpiecesyou’reinterestedin. Suppose,forinstance,thatyouhaveafileof linesthatconsistofnamesintheform Smith,A.B. Jones,C. andsoon,andyouwanttheinitialstoprecedethe name,asin A.B.Smith C.Jones Itispossibletodothiswithaseriesofediting commands,butitistediousanderror-prone.(Itis instructivetofigureouthowitisdone,though.) Thealternativeisto‘tag’thepiecesofthe pattern(inthiscase,thelastname,andtheinitials),andthenrearrangethepieces.Ontheleft sideofasubstitution,ifpartofthepatternis enclosedbetween\\(and\\),whatevermatched thatpartisremembered,andavailableforuseon therightside.Ontherightside,thesymbol‘\\1’ referstowhatevermatchedthefirst\\(...\\)pair, ‘\\2’tothesecond\\(...\\),andsoon. Thecommand 1,$s/ˆ \\([ˆ ,]∗\\),∗\\(.∗\\)/\\2\\1/ althoughhardtoread,doesthejob.Thefirst \\(...\\)matchesthelastname,whichisanystring uptothecomma;thisisreferredtoontheright sidewith‘\\1’.Thesecond\\(...\\)iswhateverfollowsthecommaandanyspaces,andisreferredto as‘\\2’. Ofcourse,withanyeditingsequencethis complicated,it’sfoolhardytosimplyrunitand hope.Theglobalcommandsgandvdiscussedin section4provideawayforyoutoprintexactly thoselineswhichwereaffectedbythesubstitute command,andthusverifythatitdidwhatyou wantedinallcases. 3.LINEADDRESSINGINTHEEDITOR Thenextgeneralareawewilldiscussisthat oflineaddressingined,thatis,howyouspecify whatlinesaretobeaffectedbyeditingcommands. Wehavealreadyusedconstructionslike 1,$s/x/y/ tospecifyachangeonalllines.Andmostusers arelongsincefamiliarwithusingasinglenewline (orreturn)toprintthenextline,andwith /thing/ tofindalinethatcontains‘thing’.Lessfamiliar, surprisinglyenough,istheuseof ?thing? toscanbackwardsforthepreviousoccurrenceof ‘thing’.Thisisespeciallyhandywhenyourealize thatthethingyouwanttooperateonisbackup thepagefromwhereyouarecurrentlyediting. Theslashandquestionmarkaretheonly charactersyoucanusetodelimitacontextsearch, thoughyoucanuseessentiallyanycharacterina substitutecommand. AddressArithmetic Thenextstepistocombinethelinenumberslike‘.’,‘$’,‘/.../’and‘?...?’with‘+’and‘−’. Thus $−1 isacommandtoprintthenexttolastlineofthe currentfile(thatis,onelinebeforeline‘$’).For example,torecallhowfaryougotinaprevious editingsession, $−5,$p printsthelastsixlines.(Besureyouunderstand whyit’ssix,notfive.)Iftherearen’tsix,of course,you’llgetanerrormessage. Asanotherexample, .−3,.+3p printsfromthreelinesbeforewhereyouarenow (atlinedot)tothreelinesafter,thusgivingyoua bitofcontext.Bytheway,the‘+’canbeomitted: .−3,.3p isabsolutelyidenticalinmeaning. Anotherareainwhichyoucansavetyping effortinspecifyinglinesistouse‘−’and‘+’as linenumbersbythemselves. − byitselfisacommandtomovebackuponelinein thefile.Infact,youcanstringseveralminussigns togethertomovebackupthatmanylines: −−− movesupthreelines,asdoes‘−3’.Thus −3,+3p isalsoidenticaltotheexamplesabove. Since‘−’isshorterthan‘.−1’,constructions like −,.s/bad/good/ areuseful.Thischanges‘bad’to‘good’onthepreviouslineandonthecurrentline.

-8- ‘+’and‘−’canbeusedincombinationwith searchesusing‘/.../’and‘?...?’,andwith‘$’.The search /thing/−− findsthelinecontaining‘thing’,andpositionsyou twolinesbeforeit. RepeatedSearches Supposeyouaskforthesearch /horriblething/ andwhenthelineisprintedyoudiscoverthatit isn’tthehorriblethingthatyouwanted,soitis necessarytorepeatthesearchagain.Youdon’t havetore-typethesearch,fortheconstruction // isashorthandfor‘thepreviousthingthatwas searchedfor’,whateveritwas.Thiscanbe repeatedasmanytimesasnecessary.Youcanalso gobackwards: ?? searchesforthesamething,butinthereverse direction. Notonlycanyourepeatthesearch,butyou canuse‘//’astheleftsideofasubstitutecommand,tomean‘themostrecentpattern’. /horriblething/ ....edprintslinewith‘horriblething’... s//good/p Togobackwardsandchangealine,say ??s//good/ Ofcourse,youcanstillusethe‘&’ontheright handsideofasubstitutetostandforwhatevergot matched: //s//&&/p findsthenextoccurrenceofwhateveryousearched forlast,replacesitbytwocopiesofitself,then printsthelinejusttoverifythatitworked. DefaultLineNumbersandtheValueofDot Oneofthemosteffectivewaystospeedup youreditingisalwaystoknowwhatlineswillbe affectedbyacommandifyoudon’tspecifythe linesitistoacton,andonwhatlineyouwillbe positioned(i.e.,thevalueofdot)whenacommand finishes.Ifyoucaneditwithoutspecifyingunnecessarylinenumbers,youcansavealotoftyping. Asthemostobviousexample,ifyouissuea searchcommandlike /thing/ youareleftpointingatthenextlinethatcontains ‘thing’.Thennoaddressisrequiredwithcommandslikestomakeasubstitutiononthatline, orptoprintit,orltolistit,ordtodeleteit,or atoappendtextafterit,orctochangeit,orito inserttextbeforeit. Whathappensiftherewasno‘thing’? Thenyouareleftrightwhereyouwere—dotis unchanged.Thisisalsotrueifyouweresittingon theonly‘thing’whenyouissuedthecommand. Thesamerulesholdforsearchesthatuse‘?...?’; theonlydifferenceisthedirectioninwhichyou search. Thedeletecommanddleavesdotpointing atthelinethatfollowedthelastdeletedline. Whenline‘$’getsdeleted,however,dotpointsat thenewline‘$’. Theline-changingcommandsa,candiby defaultallaffectthecurrentline—ifyougiveno linenumberwiththem,aappendstextafterthe currentline,cchangesthecurrentline,andi insertstextbeforethecurrentline. a,c,andibehaveidenticallyinonerespect —whenyoustopappending,changingorinserting,dotpointsatthelastlineentered.Thisis exactlywhatyouwantfortypingandeditingon thefly.Forexample,youcansay a ...text... ...botch...(minorerror) . s/botch/correct/(fixbotchedline) a ...moretext... withoutspecifyinganylinenumberforthesubstitutecommandorforthesecondappendcommand. Oryoucansay a ...text... ...horriblebotch...(majorerror) . c(replaceentireline) ...fixedupline... Youshouldexperimenttodeterminewhat happensifyouaddnolineswitha,cori. Thercommandwillreadafileintothetext beingedited,eitherattheendifyougiveno address,orafterthespecifiedlineifyoudo.In eithercase,dotpointsatthelastlinereadin. Rememberthatyoucanevensay0rtoreadafile inatthebeginningofthetext.(Youcanalsosay 0aor1itostartaddingtextatthebeginning.) Thewcommandwritesouttheentirefile. Ifyouprecedethecommandbyonelinenumber, thatlineiswritten,whileifyouprecedeitbytwo -9-linenumbers,thatrangeoflinesiswritten.The wcommanddoesnotchangedot:thecurrentline remainsthesame,regardlessofwhatlinesare written.Thisistrueevenifyousaysomething like /ˆ \\.AB/,/ˆ \\.AE/wabstract whichinvolvesacontextsearch. Sincethewcommandissoeasytouse,you shouldsavewhatyouareeditingregularlyasyou goalongjustincasethesystemcrashes,orincase youdosomethingfoolish,likeclobberingwhat you’reediting. Theleastintuitivebehavior,inasense,is thatofthescommand.Theruleissimple—you areleftsittingonthelastlinethatgotchanged.If therewerenochanges,thendotisunchanged. Toillustrate,supposethattherearethree linesinthebuffer,andyouaresittingonthemiddleone: x1 x2 x3 Thenthecommand −,+s/x/y/p printsthethirdline,whichisthelastonechanged. Butifthethreelineshadbeen x1 y2 y3 andthesamecommandhadbeenissuedwhiledot pointedatthesecondline,thentheresultwould betochangeandprintonlythefirstline,andthat iswheredotwouldbeset. Semicolon‘;’ Searcheswith‘/.../’and‘?...?’startatthe currentlineandmoveforwardorbackwardrespectivelyuntiltheyeitherfindthepatternorgetback tothecurrentline.Sometimesthisisnotwhatis wanted.Suppose,forexample,thatthebuffer containslineslikethis: . . . ab . . . bc . . Startingatline1,onewouldexpectthatthecommand /a/,/b/p printsallthelinesfromthe‘ab’tothe‘bc’inclusive.Actuallythisisnotwhathappens.Both searches(for‘a’andfor‘b’)startfromthesame point,andthustheybothfindthelinethatcontains‘ab’.Theresultistoprintasingleline. Worse,iftherehadbeenalinewitha‘b’init beforethe‘ab’line,thentheprintcommandwould beinerror,sincethesecondlinenumberwouldbe lessthanthefirst,anditisillegaltotrytoprint linesinreverseorder. Thisisbecausethecommaseparatorforline numbersdoesn’tsetdotaseachaddressisprocessed;eachsearchstartsfromthesameplace.In ed,thesemicolon‘;’canbeusedjustlikecomma, withthesingledifferencethatuseofasemicolon forcesdottobesetatthatpointasthelinenumbersarebeingevaluated.Ineffect,thesemicolon ‘moves’dot.Thusinourexampleabove,thecommand /a/;/b/p printstherangeoflinesfrom‘ab’to‘bc’,because afterthe‘a’isfound,dotissettothatline,and then‘b’issearchedfor,startingbeyondthatline. Thispropertyismostoftenusefulinavery simplesituation.Supposeyouwanttofindthe secondoccurrenceof‘thing’.Youcouldsay /thing/ // butthisprintsthefirstoccurrenceaswellasthe second,andisanuisancewhenyouknowverywell thatitisonlythesecondoneyou’reinterestedin. Thesolutionistosay /thing/;// Thissaystofindthefirstoccurrenceof‘thing’,set dottothatline,thenfindthesecondandprint onlythat. Closelyrelatedissearchingforthesecond previousoccurrenceofsomething,asin ?something?;?? Printingthethirdorfourthor...ineitherdirectionisleftasanexercise. Finally,bearinmindthatifyouwantto findthefirstoccurrenceofsomethinginafile, startingatanarbitraryplacewithinthefile,itis notsufficienttosay 1;/thing/ becausethisfailsif‘thing’occursonline1.Butit ispossibletosay 0;/thing/ (oneofthefewplaceswhere0isalegalline -10-number),forthisstartsthesearchatline1. InterruptingtheEditor Asafinalnoteonwhatdotgetssetto,you shouldbeawarethatifyouhittheinterruptor deleteorruboutorbreakkeywhileedisdoinga command,thingsareputbacktogetheragainand yourstateisrestoredasmuchaspossibletowhat itwasbeforethecommandbegan.Naturally, somechangesareirrevocable—ifyouarereading orwritingafileormakingsubstitutionsordeletinglines,thesewillbestoppedinsomecleanbut unpredictablestateinthemiddle(whichiswhyit isnotusuallywisetostopthem).Dotmayor maynotbechanged. Printingismoreclearcut.Dotisnot changeduntiltheprintingisdone.Thusifyou printuntilyouseeaninterestingline,thenhit delete,youarenotsittingonthatlineorevennear it.Dotisleftwhereitwaswhenthepcommand wasstarted. 4.GLOBALCOMMANDS Theglobalcommandsgandvareusedto performoneormoreeditingcommandsonalllines thateithercontain(g)ordon’tcontain(v)aspecifiedpattern. Asthesimplestexample,thecommand g/UNIX/p printsalllinesthatcontaintheword‘UNIX’.The patternthatgoesbetweentheslashescanbeanythingthatcouldbeusedinalinesearchorina substitutecommand;exactlythesamerulesand limitationsapply. Asanotherexample,then, g/ˆ \\./p printsalltheformattingcommandsinafile(lines thatbeginwith‘.’). Thevcommandisidenticaltog,except thatitoperatesonthoselinethatdonotcontain anoccurrenceofthepattern.(Don’tlooktoo hardformnemonicsignificancetotheletter‘v’.) So v/ˆ \\./p printsallthelinesthatdon’tbeginwith‘.’—the actualtextlines. Thecommandthatfollowsgorvcanbe anything: g/ˆ \\./d deletesalllinesthatbeginwith‘.’,and g/ˆ $/d deletesallemptylines.

Probablythemostusefulcommandthatcan followaglobalisthesubstitutecommand,forthis canbeusedtomakeachangeandprinteach affectedlineforverification.Forexample,we couldchangetheword‘Unix’to‘UNIX’everywhere,andverifythatitreallyworked,with g/Unix/s//UNIX/gp Noticethatweused‘//’inthesubstitutecommandtomean‘thepreviouspattern’,inthiscase, ‘Unix’.Thepcommandisdoneoneverylinethat matchesthepattern,notjustthoseonwhicha substitutiontookplace. Theglobalcommandoperatesbymaking twopassesoverthefile.Onthefirstpass,alllines thatmatchthepatternaremarked.Onthesecondpass,eachmarkedlineinturnisexamined, dotissettothatline,andthecommandexecuted. Thismeansthatitispossibleforthecommand thatfollowsagorvtouseaddresses,setdot,and soon,quitefreely. g/ˆ \\.PP/+ printsthelinethatfollowseach‘.PP’command (thesignalforanewparagraphinsomeformatting packages).Rememberthat‘+’means‘oneline pastdot’.And g/topic/?ˆ \\.SH?1 searchesforeachlinethatcontains‘topic’,scans backwardsuntilitfindsalinethatbegins‘.SH’(a sectionheading)andprintsthelinethatfollows that,thusshowingthesectionheadingsunder which‘topic’ismentioned.Finally, g/ˆ \\.EQ/+,/ˆ \\.EN/−p printsallthelinesthatliebetweenlinesbeginning with‘.EQ’and‘.EN’formattingcommands. Thegandvcommandscanalsobeprecededbylinenumbers,inwhichcasethelines searchedareonlythoseintherangespecified. Multi-lineGlobalCommands Itispossibletodomorethanonecommand underthecontrolofaglobalcommand,although thesyntaxforexpressingtheoperationisnotespeciallynaturalorpleasant.Asanexample,suppose thetaskistochange‘x’to‘y’and‘a’to‘b’onall linesthatcontain‘thing’.Then g/thing/s/x/y/\\ s/a/b/ issufficient.The‘\\’signalsthegcommandthat thesetofcommandscontinuesonthenextline;it terminatesonthefirstlinethatdoesnotendwith ‘\\’.(Asaminorblemish,youcan’tuseasubstitutecommandtoinsertanewlinewithinagcommand.)

-11-Youshouldwatchoutforthisproblem:the command g/x/s//y/\\ s/a/b/ doesnotworkasyouexpect.Theremembered patternisthelastpatternthatwasactuallyexecuted,sosometimesitwillbe‘x’(asexpected), andsometimesitwillbe‘a’(notexpected).You mustspellitout,likethis: g/x/s/x/y/\\ s/a/b/ Itisalsopossibletoexecutea,candicommandsunderaglobalcommand;aswithother multi-lineconstructions,allthatisneededisto adda‘\\’attheendofeachlineexceptthelast. Thustoadda‘.nf’and‘.sp’commandbeforeeach ‘.EQ’line,type g/ˆ \\.EQ/i\\ .nf\\ .sp Thereisnoneedforafinallinecontaininga‘.’to terminatetheicommand,unlesstherearefurther commandsbeingdoneundertheglobal.Onthe otherhand,itdoesnoharmtoputitineither. 5.CUTANDPASTEWITHUNIXCOM-MANDS Oneeditingareainwhichnon-programmers seemnotveryconfidentisinwhatmightbecalled ‘cutandpaste’operations—changingthenameof afile,makingacopyofafilesomewhereelse,movingafewlinesfromoneplacetoanotherinafile, insertingonefileinthemiddleofanother,splitting afileintopieces,andsplicingtwoormorefiles together. Yetmostoftheseoperationsareactually quiteeasy,ifyoukeepyourwitsaboutyouandgo cautiously.Thenextseveralsectionstalkabout cutandpaste.WewillbeginwiththeUNIXcommandsformovingentirefilesaround,thendiscuss edcommandsforoperatingonpiecesoffiles. ChangingtheNameofaFile Youhaveafilenamed‘memo’andyouwant ittobecalled‘paper’instead.Howisitdone? TheUNIXprogramthatrenamesfilesis calledmv(for‘move’);it‘moves’thefilefromone nametoanother,likethis: mvmemopaper That’sallthereistoit:mvfromtheoldnameto thenewname. mvoldnamenewname Warning:ifthereisalreadyafilearoundwiththe newname,itspresentcontentswillbesilently clobberedbytheinformationfromtheotherfile. Theoneexceptionisthatyoucan’tmoveafileto itself— mvxx isillegal. MakingaCopyofaFile Sometimeswhatyouwantisacopyofafile —anentirelyfreshversion.Thismightbe becauseyouwanttoworkonafile,andyetsavea copyincasesomethinggetsfouledup,orjust becauseyou’reparanoid. Inanycase,thewaytodoitiswiththecp command.(cpstandsfor‘copy’;thesystemisbig onshortcommandnames,whichareappreciated byheavyusers,butsometimesastrainfor novices.)Supposeyouhaveafilecalled‘good’and youwanttosaveacopybeforeyoumakesome dramaticeditingchanges.Chooseaname— ‘savegood’mightbeacceptable—thentype cpgoodsavegood Thiscopies‘good’onto‘savegood’,andyounow havetwoidenticalcopiesofthefile‘good’.(If ‘savegood’previouslycontainedsomething,itgets overwritten.) Nowifyoudecideatsometimethatyou wanttogetbacktotheoriginalstateof‘good’, youcansay mvsavegoodgood (ifyou’renotinterestedin‘savegood’anymore), or cpsavegoodgood ifyoustillwanttoretainasafecopy. Insummary,mvjustrenamesafile;cp makesaduplicatecopy.Bothofthemclobberthe ‘target’fileifitalreadyexists,soyouhadbetter besurethat’swhatyouwanttodobeforeyoudo it. RemovingaFile Ifyoudecideyouarereallydonewithafile forever,youcanremoveitwiththermcommand: rmsavegood throwsaway(irrevocably)thefilecalled‘savegood’. PuttingTwoorMoreFilesTogether Thenextstepisthefamiliaroneofcollectingtwoormorefilesintoonebigone.Thiswillbe needed,forexample,whentheauthorofapaper -12-decidesthatseveralsectionsneedtobecombined intoone.Thereareseveralwaystodoit,ofwhich thecleanest,onceyougetusedtoit,isaprogram calledcat.(Notallprogramshavetwo-letter names.)catisshortfor‘concatenate’,whichis exactlywhatwewanttodo. Supposethejobistocombinethefiles‘file1’ and‘file2’intoasinglefilecalled‘bigfile’.Ifyou say catfile thecontentsof‘file’willgetprintedonyourterminal.Ifyousay catfile1file2 thecontentsof‘file1’andthenthecontentsof ‘file2’willbothbeprintedonyourterminal,inthat order.Socatcombinesthefiles,allright,butit’s notmuchhelptoprintthemontheterminal—we wantthemin‘bigfile’. Fortunately,thereisaway.Youcantellthe systemthatinsteadofprintingonyourterminal, youwantthesameinformationputinafile.The waytodoitistoaddtothecommandlinethe character>andthenameofthefilewhereyou wanttheoutputtogo.Thenyoucansay catfile1file2>bigfile andthejobisdone.(Aswithcpandmv,you’re puttingsomethinginto‘bigfile’,andanythingthat wasalreadythereisdestroyed.) Thisabilityto‘capture’theoutputofaprogramisoneofthemostusefulaspectsofthesystem.Fortunatelyit’snotlimitedtothecatprogram—youcanuseitwithanyprogramthat printsonyourterminal.We’llseesomemoreuses foritinamoment. Naturally,youcancombineseveralfiles,not justtwo: catfile1file2file3...>bigfile collectsawholebunch. Question:isthereanydifferencebetween cpgoodsavegood and catgood>savegood Answer:formostpurposes,no.Youmightreasonablyaskwhytherearetwoprogramsinthatcase, sincecatisobviouslyallyouneed.Theansweris thatcpwilldosomeotherthingsaswell,which youcaninvestigateforyourselfbyreadingthe manual.Fornowwe’llsticktosimpleusages.

AddingSomethingtotheEndofaFile Sometimesyouwanttoaddonefiletothe endofanother.Wehaveenoughbuildingblocks nowthatyoucandoit;infactbeforereadingfurtheritwouldbevaluableifyoufiguredouthow. Tobespecific,howwouldyouusecp,mvand/or cattoaddthefile‘good1’totheendofthefile ‘good’? Youcouldtry catgoodgood1>temp mvtempgood whichisprobablymostdirect.Youshouldalso understandwhy catgoodgood1>good doesn’twork.(Don’tpracticewithagood ‘good’!) Theeasywayistouseavariantof>,called >>.Infact,>>isidenticalto>exceptthat insteadofclobberingtheoldfile,itsimplytacks stuffonattheend.Thusyoucouldsay catgood1>>good and‘good1’isaddedtotheendof‘good’.(Andif ‘good’didn’texist,thismakesacopyof‘good1’ called‘good’.) 6.CUTANDPASTEWITHTHEEDI-TOR Nowwemoveontomanipulatingpiecesof files—individuallinesorgroupsoflines.Thisis anotherareawherenewusersseemunsureof themselves. Filenames Thefirststepistoensurethatyouknowthe edcommandsforreadingandwritingfiles.Of courseyoucan’tgoveryfarwithoutknowingr andw.Equallyuseful,butlesswellknown,isthe ‘edit’commande.Withined,thecommand enewfile says‘Iwanttoeditanewfilecallednewfile,withoutleavingtheeditor.’Theecommanddiscards whateveryou’recurrentlyworkingonandstarts overonnewfile.It’sexactlythesameasifyou hadquitwiththeqcommand,thenre-entereded withanewfilename,exceptthatifyouhavea patternremembered,thenacommandlike//will stillwork. Ifyouenteredwiththecommand edfile edremembersthenameofthefile,andanysubsequente,rorwcommandsthatdon’tcontaina filenamewillrefertothisrememberedfile.Thus -13-edfile1 ...(editing)... w(writesbackinfile1) efile2(editnewfile,withoutleavingeditor) ...(editingonfile2)... w(writesbackonfile2) (andsoon)doesaseriesofeditsonvariousfiles withouteverleavingedandwithouttypingthe nameofanyfilemorethanonce.(Asanaside,if youexaminethesequenceofcommandshere,you canseewhymanyUNIXsystemsuseeasasynonymfored.) Youcanfindouttherememberedfilename atanytimewiththefcommand;justtypefwithoutafilename.Youcanalsochangethenameof therememberedfilenamewithf;ausefulsequence is edprecious fjunk ...(editing)... whichgetsacopyofapreciousfile,thenusesfto guaranteethatacarelesswcommandwon’tclobbertheoriginal. InsertingOneFileintoAnother Supposeyouhaveafilecalled‘memo’,and youwantthefilecalled‘table’tobeinsertedjust afterthereferencetoTable1.Thatis,in‘memo’ somewhereisalinethatsays Table1showsthat... andthedatacontainedin‘table’hastogothere, probablysoitwillbeformattedproperlybynroff ortroff.Nowwhat? Thisoneiseasy.Edit‘memo’,find‘Table 1’,andaddthefile‘table’rightthere: edmemo /Table1/ Table1showsthat...[responsefromed] .rtable Thecriticallineisthelastone.Aswesaidearlier, thercommandreadsafile;hereyouaskedforit tobereadinrightafterlinedot.Anrcommand withoutanyaddressaddslinesattheend,soitis thesameas$r. WritingoutPartofaFile Theothersideofthecoiniswritingout partofthedocumentyou’reediting.Forexample, maybeyouwanttosplitoutintoaseparatefile thattablefromthepreviousexample,soitcanbe formattedandtestedseparately.Supposethatin thefilebeingeditedwehave .TS ...[lotsofstuff] .TE whichisthewayatableissetupforthetblprogram.Toisolatethetableinaseparatefilecalled ‘table’,firstfindthestartofthetable(the‘.TS’ line),thenwriteouttheinterestingpart: /ˆ \\.TS/ .TS[edprintsthelineitfound] .,/ˆ \\.TE/wtable andthejobisdone.Ifyouareconfident,youcan doitallatoncewith /ˆ \\.TS/;/ˆ \\.TE/wtable Thepointisthatthewcommandcanwrite outagroupoflines,insteadofthewholefile.In fact,youcanwriteoutasinglelineifyoulike;just giveonelinenumberinsteadoftwo.Forexample, ifyouhavejusttypedahorriblycomplicatedline andyouknowthatit(orsomethinglikeit)is goingtobeneededlater,thensaveit—don’tretypeit.Intheeditor,say a ...lotsofstuff... ...horribleline... . .wtemp a ...morestuff... . .rtemp a ...morestuff... . Thislastexampleisworthstudying,tobesure youappreciatewhat’sgoingon. MovingLinesAround Supposeyouwanttomoveaparagraph fromitspresentpositioninapapertotheend. Howwouldyoudoit?Asaconcreteexample, supposeeachparagraphinthepaperbeginswith theformattingcommand‘.PP’.Thinkaboutit andwritedownthedetailsbeforereadingon. Thebruteforceway(notnecessarilybad)is towritetheparagraphontoatemporaryfile, deleteitfromitscurrentposition,thenreadinthe temporaryfileattheend.Assumingthatyouare sittingonthe‘.PP’commandthatbeginsthe paragraph,thisisthesequenceofcommands: .,/ˆ \\.PP/−wtemp .,//−d $rtemp Thatis,fromwhereyouarenow(‘.’)untilone linebeforethenext‘.PP’(‘/ˆ \\.PP/−’)writeonto -14- ‘temp’.Thendeletethesamelines.Finally,read ‘temp’attheend. Aswesaid,that’sthebruteforceway.The easierway(often)istousethemovecommandm thatedprovides—itletsyoudothewholesetof operationsatonecrack,withoutanytemporary file. Themcommandislikemanyotheredcommandsinthatittakesuptotwolinenumbersin frontthattellwhatlinesaretobeaffected.Itis alsofollowedbyalinenumberthattellswherethe linesaretogo.Thus line1,line2mline3 saystomoveallthelinesbetween‘line1’and ‘line2’after‘line3’.Naturally,anyof‘line1’etc., canbepatternsbetweenslashes,$signs,orother waystospecifylines. Supposeagainthatyou’resittingatthefirst lineoftheparagraph.Thenyoucansay .,/ˆ \\.PP/−m$ That’sall. Asanotherexampleofafrequentoperation, youcanreversetheorderoftwoadjacentlinesby movingthefirstonetoafterthesecond.Suppose thatyouarepositionedatthefirst.Then m+ doesit.Itsaystomovelinedottoafteroneline afterlinedot.Ifyouarepositionedonthesecond line, m−− doestheinterchange. Asyoucansee,themcommandismore succinctanddirectthanwriting,deletingandrereading.Whenisbruteforcebetteranyway? Thisisamatterofpersonaltaste—dowhatyou havemostconfidencein.Themaindifficultywith themcommandisthatifyouusepatternsto specifyboththelinesyouaremovingandthetarget,youhavetotakecarethatyouspecifythem properly,oryoumaywellnotmovethelinesyou thoughtyoudid.Theresultofabotchedmcommandcanbeaghastlymess.Doingthejobastep atatimemakesiteasierforyoutoverifyateach stepthatyouaccomplishedwhatyouwantedto. It’salsoagoodideatoissueawcommandbefore doinganythingcomplicated;thenifyougoof,it’s easytobackuptowhereyouwere. Marks edprovidesafacilityformarkingaline withaparticularnamesoyoucanlaterreference itbynameregardlessofitsactuallinenumber. Thiscanbehandyformovinglines,andfor keepingtrackofthemastheymove.Themark commandisk;thecommand kx marksthecurrentlinewiththename‘x’.Ifaline numberprecedesthek,thatlineismarked.(The marknamemustbeasinglelowercaseletter.) Nowyoucanrefertothemarkedlinewiththe address ′x Marksaremostusefulformovingthings around.Findthefirstlineoftheblocktobe moved,andmarkitwith′a.Thenfindthelast lineandmarkitwith′b.Nowpositionyourselfat theplacewherethestuffistogoandsay ′a,′bm. Bearinmindthatonlyonelinecanhavea particularmarknameassociatedwithitatany giventime. CopyingLines Wementionedearliertheideaofsavinga linethatwashardtotypeorusedoften,soasto cutdownontypingtime.Ofcoursethiscouldbe morethanoneline;thenthesavingispresumably evengreater. edprovidesanothercommand,calledt(for ‘transfer’)formakingacopyofagroupofoneor morelinesatanypoint.Thisisofteneasierthan writingandreading. Thetcommandisidenticaltothemcommand,exceptthatinsteadofmovinglinesitsimplyduplicatesthemattheplaceyounamed.Thus 1,$t$ duplicatestheentirecontentsthatyouareediting. Amorecommonusefortisforcreatingaseriesof linesthatdifferonlyslightly.Forexample,you cansay a ..........x.........(longline) . t.(makeacopy) s/x/y/(changeitabit) t.(makethirdcopy) s/y/z/(changeitabit) andsoon. TheTemporaryEscape‘!’ Sometimesitisconvenienttobeableto temporarilyescapefromtheeditortodosome otherUNIXcommand,perhapsoneofthefilecopy ormovecommandsdiscussedinsection5,without leavingtheeditor.The‘escape’command!

-15-providesawaytodothis. Ifyousay !anyUNIXcommand yourcurrenteditingstateissuspended,andthe UNIXcommandyouaskedforisexecuted.When thecommandfinishes,edwillsignalyoubyprintinganother!;atthatpointyoucanresumeediting. YoucanreallydoanyUNIXcommand, includinganothered.(Thisisquitecommon,in fact.)Inthiscase,youcanevendoanother!. 7.SUPPORTINGTOOLS Thereareseveraltoolsandtechniquesthat goalongwiththeeditor,allofwhicharerelatively easyonceyouknowhowedworks,becausethey areallbasedontheeditor.Inthissectionwewill givesomefairlycursoryexamplesofthesetools, moretoindicatetheirexistencethantoprovidea completetutorial.Moreinformationoneachcan befoundin[3]. Grep Sometimesyouwanttofindalloccurrences ofsomewordorpatterninasetoffiles,toedit themorperhapsjusttoverifytheirpresenceor absence.Itmaybepossibletoediteachfileseparatelyandlookforthepatternofinterest,butif therearemanyfilesthiscangetverytedious,and ifthefilesarereallybig,itmaybeimpossible becauseoflimitsined. Theprogramgrepwasinventedtoget aroundtheselimitations.Thesearchpatternsthat wehavedescribedinthepaperareoftencalled ‘regularexpressions’,and‘grep’standsfor g/re/p Thatdescribesexactlywhatgrepdoes—itprints everylineinasetoffilesthatcontainsaparticular pattern.Thus grep′thing′file1file2file3... finds‘thing’whereveritoccursinanyofthefiles ‘file1’,‘file2’,etc.grepalsoindicatesthefilein whichthelinewasfound,soyoucanlateredititif youlike. Thepatternrepresentedby‘thing’canbe anypatternyoucanuseintheeditor,sincegrep andeduseexactlythesamemechanismforpatternsearching.Itiswisestalwaystoenclosethe patterninthesinglequotes′...′ifitcontainsany non-alphabeticcharacters,sincemanysuchcharac-tersalsomeansomethingspecialtotheUNIXcom-mandinterpreter(the‘shell’).Ifyoudon’tquote them,thecommandinterpreterwilltrytointerpretthembeforegrepgetsachance.

Thereisalsoawaytofindlinesthatdon’t containapattern: grep−v′thing′file1file2... findsalllinesthatdon’tcontains‘thing’.The−v mustoccurinthepositionshown.Givengrep andgrep−v,itispossibletodothingslikeselectingalllinesthatcontainsomecombinationofpatterns.Forexample,togetalllinesthatcontain‘x’ butnot‘y’: grepxfile...|grep−vy (Thenotation|isa‘pipe’,whichcausestheoutputofthefirstcommandtobeusedasinputto thesecondcommand;see[2].) EditingScripts Ifafairlycomplicatedsetofeditingoperationsistobedoneonawholesetoffiles,theeasiestthingtodoistomakeupa‘script’,i.e.,afile thatcontainstheoperationsyouwanttoperform, thenapplythisscripttoeachfileinturn. Forexample,supposeyouwanttochange every‘Unix’to‘UNIX’andevery‘Gcos’to ‘GCOS’inalargenumberoffiles.Thenputinto thefile‘script’thelines g/Unix/s//UNIX/g g/Gcos/s//GCOS/g w q Nowyoucansay edfile1<script edfile2<script ... Thiscausesedtotakeitscommandsfromthepreparedscript.Noticethatthewholejobhastobe plannedinadvance. AndofcoursebyusingtheUNIXcommand interpreter,youcancyclethroughasetoffiles automatically,withvaryingdegreesofease. Sed sed(‘streameditor’)isaversionoftheeditorwithrestrictedcapabilitiesbutwhichiscapableofprocessingunlimitedamountsofinput. Basicallysedcopiesitsinputtoitsoutput,applyingoneormoreeditingcommandstoeachlineof input. Asanexample,supposethatwewanttodo the‘Unix’to‘UNIX’partoftheexamplegiven above,butwithoutrewritingthefiles.Thenthe command sed′s/Unix/UNIX/g′file1file2... appliesthecommand‘s/Unix/UNIX/g’toalllines -16-from‘file1’,‘file2’,etc.,andcopiesalllinestothe output.Theadvantageofusingsedinsuchacase isthatitcanbeusedwithinputtoolargefored tohandle.Alltheoutputcanbecollectedinone place,eitherinafileorperhapspipedintoanother program. Iftheeditingtransformationissocomplicatedthatmorethanoneeditingcommandis needed,commandscanbesuppliedfromafile,or onthecommandline,withaslightlymorecomplexsyntax.Totakecommandsfromafile,for example, sed−fcmdfileinput−files... sedhasfurthercapabilities,includingconditionaltestingandbranching,whichwecannotgo intohere. Acknowledgement IamgratefultoTedDolottaforhiscareful readingandvaluablesuggestions. References [1]BrianW.Kernighan,ATutorialIntroductiontotheUNIXTextEditor,BellLaboratoriesinternalmemorandum. [2]BrianW.Kernighan,UNIXForBeginners, BellLaboratoriesinternalmemorandum. [3]KenL.ThompsonandDennisM.Ritchie, TheUNIXProgrammer’sManual.Bell Laboratories.