ATutorialIntroductiontotheUNIXTextEditor BrianW.Kernighan ABSTRACT AlmostalltextinputontheUNIX◯roperatingsystemisdonewiththetexteditored.Thismemorandumisatutorialguidetohelpbeginnersgetstarted withtextediting. Althoughitdoesnotcovereverything,itdoesdiscussenoughformostusers’ day-to-dayneeds.Thisincludesprinting,appending,changing,deleting,moving andinsertingentirelinesoftext;readingandwritingfiles;contextsearchingand lineaddressing;thesubstitutecommand;theglobalcommands;andtheuseof specialcharactersforadvancedediting. 8April1993 ATutorialIntroductiontotheUNIXTextEditor BrianW.Kernighan Introduction Edisa‘‘texteditor’’,thatis,aninteractive programforcreatingandmodifying‘‘text’’,using directionsprovidedbyauserataterminal.The textisoftenadocumentlikethisone,oraprogramorperhapsdataforaprogram. Thisintroductionismeanttosimplifylearning ed.Therecommendedwaytolearnedistoread thisdocument,simultaneouslyusingedtofollow theexamples,thentoreadthedescriptioninsectionIoftheUNIXProgrammer’sManual,allthe whileexperimentingwithed.(Solicitationof advicefromexperiencedusersisalsouseful.) Dotheexercises!Theycovermaterialnot completelydiscussedintheactualtext.An appendixsummarizesthecommands. Disclaimer Thisisanintroductionandatutorial.Forthis reason,noattemptismadetocovermorethana partofthefacilitiesthatedoffers(althoughthis fractionincludesthemostusefulandfrequently usedparts).WhenyouhavemasteredtheTutorial,tryAdvancedEditingonUNIX.Also,thereis notenoughspacetoexplainbasicUNIXprocedures.Wewillassumethatyouknowhowtolog ontoUNIX,andthatyouhaveatleastavague understandingofwhatafileis.Formoreonthat, readUNIXforBeginners. Youmustalsoknowwhatcharactertotypeas theend-of-lineonyourparticularterminal.This characteristheRETURNkeyonmostterminals. Throughout,wewillrefertothischaracter,whateveritis,asRETURN. GettingStarted We’llassumethatyouhaveloggedintoyour systemandithasjustprintedthepromptcharacter,usuallyeithera$ora%.Theeasiestwayto getedistotype eedd((ffoolllloowweeddbbyyaarreettuurrnn)) Youarenowreadytogo−ediswaitingforyouto tellitwhattodo. CreatingText−theAppendcommand‘‘a’’ Asyourfirstproblem,supposeyouwantto createsometextstartingfromscratch.Perhaps youaretypingtheveryfirstdraftofapaper; clearlyitwillhavetostartsomewhere,and undergomodificationslater.Thissectionwill showhowtogetsometextin,justtogetstarted. Laterwe’lltalkabouthowtochangeit. Whenedisfirststarted,itisratherlikeworkingwithablankpieceofpaper−thereisnotext orinformationpresent.Thismustbesuppliedby thepersonusinged;itisusuallydonebytypingin thetext,orbyreadingitintoedfromafile.We willstartbytypinginsometext,andreturn shortlytohowtoreadfiles. Firstabitofterminology.Inedjargon,the textbeingworkedonissaidtobe‘‘keptina buffer.’’Thinkofthebufferasaworkspace,if youlike,orsimplyastheinformationthatyouare goingtobeediting.Ineffectthebufferislikethe pieceofpaper,onwhichwewillwritethings,then changesomeofthem,andfinallyfilethewhole thingawayforanotherday. Theusertellsedwhattodotohistextbytypinginstructionscalled‘‘commands.’’Mostcommandsconsistofasingleletter,whichmustbe typedinlowercase.Eachcommandistypedona separateline.(Sometimesthecommandisprecededbyinformationaboutwhatlineorlinesof textaretobeaffected−wewilldiscussthese shortly.)Edmakesnoresponsetomostcommands−thereisnopromptingortypingofmessageslike‘‘ready’’.(Thissilenceispreferredby experiencedusers,butsometimesahangupfor beginners.) Thefirstcommandisappend,writtenasthe letter aa allbyitself.Itmeans‘‘append(oradd)textlines tothebuffer,asItypethemin.’’Appendingis ratherlikewritingfreshmaterialonapieceof paper. Sotoenterlinesoftextintothebuffer,just typeanafollowedbyaRETURN,followedbythe linesoftextyouwant,likethis: aa NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. ..

-2-Theonlywaytostopappendingistotypea linethatcontainsonlyaperiod.The‘‘.’’isused totelledthatyouhavefinishedappending.(Even experiencedusersforgetthatterminating‘‘.’’ sometimes.Ifedseemstobeignoringyou,type anextralinewithjust‘‘.’’onit.Youmaythen findyou’veaddedsomegarbagelinestoyourtext, whichyou’llhavetotakeoutlater.) Aftertheappendcommandhasbeendone,the bufferwillcontainthethreelines NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. The‘‘a’’and‘‘.’’aren’tthere,becausetheyarenot text. Toaddmoretexttowhatyoualreadyhave, justissueanotheracommand,andcontinuetyping. ErrorMessages−‘‘?’’ Ifatanytimeyoumakeanerrorinthecommandsyoutypetoed,itwilltellyoubytyping ?? Thisisaboutascrypticasitcanbe,butwith practice,youcanusuallyfigureouthowyou goofed. Writingtextoutasafile−theWritecommand‘‘w’’ It’slikelythatyou’llwanttosaveyourtextfor lateruse.Towriteoutthecontentsofthebuffer ontoafile,usethewritecommand ww followedbythefilenameyouwanttowriteon. Thiswillcopythebuffer’scontentsontothespecifiedfile(destroyinganypreviousinformationon thefile).Tosavethetextonafilenamedjunk, forexample,type wwjjuunnkk Leaveaspacebetweenwandthefilename.Ed willrespondbyprintingthenumberofcharacters itwroteout.Inthiscase,edwouldrespondwith 6688 (Rememberthatblanksandthereturncharacter attheendofeachlineareincludedinthecharactercount.)Writingafilejustmakesacopyofthe text−thebuffer’scontentsarenotdisturbed,so youcangoonaddinglinestoit.Thisisanimportantpoint.Edatalltimesworksonacopyofa file,notthefileitself.Nochangeinthecontents ofafiletakesplaceuntilyougiveawcommand. (Writingoutthetextontoafilefromtimetotime asitisbeingcreatedisagoodidea,sinceifthe systemcrashesorifyoumakesomehorriblemistake,youwillloseallthetextinthebufferbut anytextthatwaswrittenontoafileisrelatively safe.) Leavinged−theQuitcommand‘‘q’’ Toterminateasessionwithed,savethetext you’reworkingonbywritingitontoafileusing thewcommand,andthentypethecommand qq whichstandsforquit.Thesystemwillrespond withthepromptcharacter($or%).Atthispoint yourbuffervanishes,withallitstext,whichiswhy youwanttowriteitoutbeforequitting.† Exercise1: Enteredandcreatesometextusing aa ......tteexxtt...... . Writeitoutusingw.Thenleaveedwiththeq command,andprintthefile,toseethateverything worked.(Toprintafile,say pprrfifilleennaammee or ccaattfifilleennaammee inresponsetothepromptcharacter.Tryboth.) Readingtextfromafile−theEditcommand‘‘e’’ Acommonwaytogettextintothebufferisto readitfromafileinthefilesystem.Thisiswhat youdotoedittextthatyousavedwiththew commandinaprevioussession.Theeditcommandefetchestheentirecontentsofafileintothe buffer.Soifyouhadsavedthethreelines‘‘Nowis thetime’’,etc.,withawcommandinanearlier session,theedcommand eejjuunnkk wouldfetchtheentirecontentsofthefilejunk intothebuffer,andrespond 6688 whichisthenumberofcharactersinjunk.Ifanythingwasalreadyinthebuffer,itisdeletedfirst. Ifyouusetheecommandtoreadafileinto thebuffer,thenyouneednotuseafilenameafter asubsequentwcommand;edremembersthelast †Actually,edwillprint?ifyoutrytoquit withoutwriting.Atthatpoint,writeifyou want;ifnot,anotherqwillgetyououtregardless.

-3-filenameusedinanecommand,andwwillwrite onthisfile.Thusagoodwaytooperateis eedd eefifillee [[eeddiittiinnggsseessssiioonn]] ww qq Thisway,youcansimplysaywfromtimetotime, andbesecureintheknowledgethatifyougotthe filenamerightatthebeginning,youarewriting intotheproperfileeachtime. Youcanfindoutatanytimewhatfilenameed isrememberingbytypingthefilecommandf.In thisexample,ifyoutyped ff edwouldreply jjuunnkk Readingtextfromafile−theReadcommand‘‘r’’ Sometimesyouwanttoreadafileintothe bufferwithoutdestroyinganythingthatisalready there.Thisisdonebythereadcommandr.The command rrjjuunnkk willreadthefilejunkintothebuffer;itaddsitto theendofwhateverisalreadyinthebuffer.Soif youdoareadafteranedit: eejjuunnkk rrjjuunnkk thebufferwillcontaintwocopiesofthetext(six lines). NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. Likethewandecommands,rprintsthenumber ofcharactersreadin,afterthereadingoperationis complete. Generallyspeaking,rismuchlessusedthane. Exercise2: Experimentwiththeecommand−tryreading andprintingvariousfiles.Youmaygetanerror ?name,wherenameisthenameofafile;this meansthatthefiledoesn’texist,typicallybecause youspelledthefilenamewrong,orperhapsthat youarenotallowedtoreadorwriteit.Tryalternatelyreadingandappendingtoseethatthey worksimilarly.Verifythat eeddfifilleennaammee isexactlyequivalentto eedd eefifilleennaammee Whatdoes fffifilleennaammee do? Printingthecontentsofthebuffer−the Printcommand‘‘p’’ Toprintorlistthecontentsofthebuffer(or partsofit)ontheterminal,usetheprintcommand pp Thewaythisisdoneisasfollows.Specifythe lineswhereyouwantprintingtobeginandwhere youwantittoend,separatedbyacomma,and followedbytheletterp.Thustoprintthefirst twolinesofthebuffer,forexample,(thatis,lines 1through2)say 11,,22pp((ssttaarrttiinngglliinnee==11,,eennddiinngglliinnee==22pp)) Edwillrespondwith NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn Supposeyouwanttoprintallthelinesinthe buffer.Youcoulduse1,3pasaboveifyouknew therewereexactly3linesinthebuffer.Butin general,youdon’tknowhowmanythereare,so whatdoyouusefortheendinglinenumber?Ed providesashorthandsymbolfor‘‘linenumberof lastlineinbuffer’’−thedollarsign$.Useitthis way: 11,,$$pp Thiswillprintallthelinesinthebuffer(line1to lastline.)Ifyouwanttostoptheprintingbefore itisfinished,pushtheDELorDeletekey;edwill type ?? andwaitforthenextcommand. Toprintthelastlineofthebuffer,youcould use $$,,$$pp butedletsyouabbreviatethisto $$pp Youcanprintanysinglelinebytypingtheline numberfollowedbyap.Thus 11pp −−44−− producestheresponse NNoowwiisstthheettiimmee whichisthefirstlineofthebuffer. Infact,edletsyouabbreviateevenfurther: youcanprintanysinglelinebytypingjusttheline number−noneedtotypetheletterp.Soifyou say $$ edwillprintthelastlineofthebuffer. Youcanalsouse$incombinationslike $$−−11,,$$pp whichprintsthelasttwolinesofthebuffer.This helpswhenyouwanttoseehowfaryougotin typing. Exercise3: Asbefore,createsometextusingtheacommandandexperimentwiththepcommand.You willfind,forexample,thatyoucan’tprintline0 oralinebeyondtheendofthebuffer,andthat attemptstoprintabufferinreverseorderbysaying 33,,11pp don’twork. Thecurrentline−‘‘Dot’’or‘‘.’’ Supposeyourbufferstillcontainsthesixlines asabove,thatyouhavejusttyped 11,,33pp andedhasprintedthethreelinesforyou.Try typingjust pp((nnoolliinneennuummbbeerrss)) Thiswillprint ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. whichisthethirdlineofthebuffer.Infactitis thelast(mostrecent)linethatyouhavedoneanythingwith.(Youjustprintedit!)Youcanrepeat thispcommandwithoutlinenumbers,anditwill continuetoprintline3. Thereasonisthatedmaintainsarecordofthe lastlinethatyoudidanythingto(inthiscase,line 3,whichyoujustprinted)sothatitcanbeused insteadofanexplicitlinenumber.Thismost recentlineisreferredtobytheshorthandsymbol ..((pprroonnoouunncceedd‘‘‘‘ddoott’’’’)).. Dotisalinenumberinthesamewaythat$is;it meansexactly‘‘thecurrentline’’,orloosely,‘‘the lineyoumostrecentlydidsomethingto.’’Youcan useitinseveralways−onepossibilityistosay ..,,$$pp Thiswillprintallthelinesfrom(including)the currentlinetotheendofthebuffer.Inourexamplethesearelines3through6. Somecommandschangethevalueofdot,while othersdonot.Thepcommandsetsdottothe numberofthelastlineprinted;thelastcommand willsetboth.and$to6. Dotismostusefulwhenusedincombinations likethisone: ..++11((oorreeqquuiivvaalleennttllyy,,..++11pp)) Thismeans‘‘printthenextline’’andisahandy waytostepslowlythroughabuffer.Youcanalso say ..−−11((oorr..−−11pp)) whichmeans‘‘printthelinebeforethecurrent line.’’Thisenablesyoutogobackwardsifyou wish.Anotherusefuloneissomethinglike ..−−33,,..−−11pp whichprintsthepreviousthreelines. Don’tforgetthatallofthesechangethevalue ofdot.Youcanfindoutwhatdotisatanytime bytyping ..== Edwillrespondbyprintingthevalueofdot. Let’ssummarizesomethingsaboutthepcommandanddot.Essentiallypcanbeprecededby 0,1,or2linenumbers.Ifthereisnolinenumber given,itprintsthe‘‘currentline’’,thelinethatdot refersto.Ifthereisonelinenumbergiven(with orwithouttheletterp),itprintsthatline(and dotissetthere);andiftherearetwolinenumbers, itprintsallthelinesinthatrange(andsetsdotto thelastlineprinted.)Iftwolinenumbersare specifiedthefirstcan’tbebiggerthanthesecond (seeExercise2.) Typingasinglereturnwillcauseprintingof thenextline−it’sequivalentto.+1p.Tryit. Trytypinga−;youwillfindthatit’sequivalent to.−1p. Deletinglines:the‘‘d’’command Supposeyouwanttogetridofthethreeextra linesinthebuffer.Thisisdonebythedeletecommand dd Exceptthatddeleteslinesinsteadofprinting them,itsactionissimilartothatofp.Thelines tobedeletedarespecifiedfordexactlyasthey areforp:

−−55−− startingline,endinglinedd Thusthecommand 44,,$$dd deleteslines4throughtheend.Therearenow threelinesleft,asyoucancheckbyusing 11,,$$pp Andnoticethat$nowisline3!Dotissettothe nextlineafterthelastlinedeleted,unlessthelast linedeletedisthelastlineinthebuffer.Inthat case,dotissetto$. Exercise4: Experimentwitha,e,r,w,pandduntilyou aresurethatyouknowwhattheydo,anduntil youunderstandhowdot,$,andlinenumbersare used. Ifyouareadventurous,tryusinglinenumbers witha,randwaswell.Youwillfindthatawill appendlinesafterthelinenumberthatyouspecify (ratherthanafterdot);thatrreadsafileinafter thelinenumberyouspecify(notnecessarilyatthe endofthebuffer);andthatwwillwriteout exactlythelinesyouspecify,notnecessarilythe wholebuffer.Thesevariationsaresometimes handy.Forinstanceyoucaninsertafileatthe beginningofabufferbysaying 00rrfifilleennaammee andyoucanenterlinesatthebeginningofthe bufferbysaying 00aa ......text...... .. Noticethat.wisverydifferentfrom .. ww Modifyingtext:theSubstitutecommand ‘‘s’’ Wearenowreadytotryoneofthemost importantofallcommands−thesubstitutecommand ss Thisisthecommandthatisusedtochangeindividualwordsorletterswithinalineorgroupof lines.Itiswhatyouuse,forexample,forcorrectingspellingmistakesandtypingerrors. Supposethatbyatypingerror,line1says NNoowwiisstthhttiimmee −theehasbeenleftoffthe.Youcanusestofix thisupasfollows:

11ss//tthh//tthhee// Thissays:‘‘inline1,substituteforthecharacters ththecharactersthe.’’Toverifythatitworks(ed willnotprinttheresultautomatically)say pp andget NNoowwiisstthheettiimmee whichiswhatyouwanted.Noticethatdotmust havebeensettothelinewherethesubstitution tookplace,sincethepcommandprintedthatline. Dotisalwayssetthiswaywiththescommand. Thegeneralwaytousethesubstitutecommandis starting-line,ending-liness//changethis//tothis// Whateverstringofcharactersisbetweenthefirst pairofslashesisreplacedbywhateverisbetween thesecondpair,inallthelinesbetweenstartinglineandending-line.Onlythefirstoccurrenceon eachlineischanged,however.Ifyouwantto changeeveryoccurrence,seeExercise5.Therules forlinenumbersarethesameasthoseforp, exceptthatdotissettothelastlinechanged. (Butthereisatrapfortheunwary:ifnosubstitutiontookplace,dotisnotchanged.Thiscauses anerror?asawarning.) Thusyoucansay 11,,$$ss//ssppeelliinngg//ssppeelllliinngg// andcorrectthefirstspellingmistakeoneachline inthetext.(Thisisusefulforpeoplewhoareconsistentmisspellers!) Ifnolinenumbersaregiven,thescommand assumeswemean‘‘makethesubstitutiononline dot’’,soitchangesthingsonlyonthecurrentline. Thisleadstotheverycommonsequence ss//ssoommeetthhiinngg//ssoommeetthhiinnggeellssee//pp whichmakessomecorrectiononthecurrentline, andthenprintsit,tomakesureitworkedout right.Ifitdidn’t,youcantryagain.(Noticethat thereisaponthesamelineasthescommand. Withfewexceptions,pcanfollowanycommand; noothermulti-commandlinesarelegal.) It’salsolegaltosay ss//......//// whichmeans‘‘changethefirststringofcharacters to‘‘nothing’’,i.e.,removethem.Thisisusefulfor deletingextrawordsinalineorremovingextra lettersfromwords.Forinstance,ifyouhad NNoowwxxxxiisstthheettiimmee youcansay −−66−− ss//xxxx////pp toget NNoowwiisstthheettiimmee Noticethat//(twoadjacentslashes)means‘‘no characters’’,notablank.Thereisadifference! (Seebelowforanothermeaningof//.) Exercise5: Experimentwiththesubstitutecommand.See whathappensifyousubstituteforsomewordona linewithseveraloccurrencesofthatword.For example,dothis: aa tthheeootthheerrssiiddeeoofftthheeccooiinn .. ss//tthhee//oonntthhee//pp Youwillget oonntthheeootthheerrssiiddeeoofftthheeccooiinn Asubstitutecommandchangesonlythefirst occurrenceofthefirststring.Youcanchangeall occurrencesbyaddingag(for‘‘global’’)tothes command,likethis: ss//......//......//ggpp Tryothercharactersinsteadofslashestodelimit thetwosetsofcharactersinthescommand− anythingshouldworkexceptblanksortabs. (Ifyougetfunnyresultsusinganyofthecharacters ˆˆ ..$$[[∗∗\\&& readthesectionon‘‘SpecialCharacters’’.) Contextsearching−‘‘/.../’’ Withthesubstitutecommandmastered,you canmoveontoanotherhighlyimportantideaof ed−contextsearching. Supposeyouhavetheoriginalthreelinetextin thebuffer: NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. Supposeyouwanttofindthelinethatcontains theirsoyoucanchangeittothe.Nowwithonly threelinesinthebuffer,it’sprettyeasytokeep trackofwhatlinethewordtheirison.Butifthe buffercontainedseveralhundredlines,andyou’d beenmakingchanges,deletingandrearranging lines,andsoon,youwouldnolongerreallyknow whatthislinenumberwouldbe.Contextsearchingissimplyamethodofspecifyingthedesired line,regardlessofwhatitsnumberis,byspecifying somecontextonit.

Thewaytosay‘‘searchforalinethatcontains thisparticularstringofcharacters’’istotype //stringofcharacterswewanttofind// Forexample,theedcommand //tthheeiirr// isacontextsearchwhichissufficienttofindthe desiredline−itwilllocatethenextoccurrenceof thecharactersbetweenslashes(‘‘their’’).Italso setsdottothatlineandprintsthelineforverification: ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. ‘‘Nextoccurrence’’meansthatedstartslookingfor thestringatline.+1,searchestotheendofthe buffer,thencontinuesatline1andsearchestoline dot.(Thatis,thesearch‘‘wrapsaround’’from$ to1.)Itscansallthelinesinthebufferuntilit eitherfindsthedesiredlineorgetsbacktodot again.Ifthegivenstringofcharacterscan’tbe foundinanyline,edtypestheerrormessage ?? Otherwiseitprintsthelineitfound. Youcandoboththesearchforthedesiredline andasubstitutionallatonce,likethis: //tthheeiirr//ss//tthheeiirr//tthhee//pp whichwillyield ttooccoommeettootthheeaaiiddoofftthheeppaarrttyy.. Therewerethreepartstothatlastcommand:contextsearchforthedesiredline,makethesubstitution,printtheline. Theexpression/their/isacontextsearch expression.Intheirsimplestform,allcontext searchexpressionsarelikethis−astringofcharacterssurroundedbyslashes.Contextsearchesare interchangeablewithlinenumbers,sotheycanbe usedbythemselvestofindandprintadesiredline, oraslinenumbersforsomeothercommand,likes. Theywereusedbothwaysintheexamplesabove. Supposethebuffercontainsthethreefamiliar lines NNoowwiisstthheettiimmee ffoorraallllggooooddmmeenn ttooccoommeettootthheeaaiiddoofftthheeiirrppaarrttyy.. Thentheedlinenumbers //NNooww//++11 //ggoooodd// //ppaarrttyy//−−11 areallcontextsearchexpressions,andtheyall refertothesameline(line2).Tomakeachange inline2,youcouldsay −−77−− //NNooww//++11ss//ggoooodd//bbaadd// or //ggoooodd//ss//ggoooodd//bbaadd// or //ppaarrttyy//−−11ss//ggoooodd//bbaadd// Thechoiceisdictatedonlybyconvenience.You couldprintallthreelinesby,forinstance //NNooww//,,//ppaarrttyy//pp or //NNooww//,,//NNooww//++22pp orbyanynumberofsimilarcombinations.The firstoneofthesemightbebetterifyoudon’t knowhowmanylinesareinvolved.(Ofcourse,if therewereonlythreelinesinthebuffer,you’duse 11,,$$pp butnotiftherewereseveralhundred.) Thebasicruleis:acontextsearchexpressionis thesameasalinenumber,soitcanbeusedwhereveralinenumberisneeded. Exercise6: Experimentwithcontextsearching.Trya bodyoftextwithseveraloccurrencesofthesame stringofcharacters,andscanthroughitusingthe samecontextsearch. Tryusingcontextsearchesaslinenumbersfor thesubstitute,printanddeletecommands.(They canalsobeusedwithr,w,anda.) Trycontextsearchingusing?text?insteadof /text/.Thisscanslinesinthebufferinreverse orderratherthannormal.Thisissometimesusefulifyougotoofarwhilelookingforsomestring ofcharacters−it’saneasywaytobackup. (Ifyougetfunnyresultswithanyofthecharacters ˆˆ ..$$[[∗∗\\&& readthesectionon‘‘SpecialCharacters’’.) Edprovidesashorthandforrepeatingacontextsearchforthesamestring.Forexample,the edlinenumber //ssttrriinngg// willfindthenextoccurrenceofstring.Itoften happensthatthisisnotthedesiredline,sothe searchmustberepeated.Thiscanbedoneby typingmerely //// Thisshorthandstandsfor‘‘themostrecentlyused contextsearchexpression.’’Itcanalsobeusedas thefirststringofthesubstitutecommand,asin //ssttrriinngg11//ss////ssttrriinngg22// whichwillfindthenextoccurrenceofstring1and replaceitbystring2.Thiscansavealotoftyping.Similarly ???? means‘‘scanbackwardsforthesameexpression.’’ ChangeandInsert−‘‘c’’and‘‘i’’ Thissectiondiscussesthechangecommand cc whichisusedtochangeorreplaceagroupofone ormorelines,andtheinsertcommand ii whichisusedforinsertingagroupofoneormore lines. ‘‘Change’’,writtenas cc isusedtoreplaceanumberoflineswithdifferent lines,whicharetypedinattheterminal.For example,tochangelines.+1through$tosomethingelse,type ..++11,,$$cc ......typethelinesoftextyouwanthere...... .. Thelinesyoutypebetweentheccommandand the.willtaketheplaceoftheoriginallines betweenstartlineandendline.Thisismostusefulinreplacingalineorseverallineswhichhave errorsinthem. Ifonlyonelineisspecifiedintheccommand, thenjustthatlineisreplaced.(Youcantypeinas manyreplacementlinesasyoulike.)Noticethe useof.toendtheinput−thisworksjustlikethe .intheappendcommandandmustappearby itselfonanewline.Ifnolinenumberisgiven, linedotisreplaced.Thevalueofdotissettothe lastlineyoutypedin. ‘‘Insert’’issimilartoappend−forinstance //ssttrriinngg//ii ......typethelinestobeinsertedhere...... .. willinsertthegiventextbeforethenextlinethat contains‘‘string’’.Thetextbetweeniand.is insertedbeforethespecifiedline.Ifnolinenumber isspecifieddotisused.Dotissettothelastline inserted.

-8-Exercise7: ‘‘Change’’isratherlikeacombinationofdelete followedbyinsert.Experimenttoverifythat start,enddd ii ...text... .. isalmostthesameas start,endcc ...text... .. Thesearenotpreciselythesameifline$gets deleted.Checkthisout.Whatisdot? Experimentwithaandi,toseethattheyare similar,butnotthesame.Youwillobservethat line-numberaa ......text...... .. appendsafterthegivenline,while line-numberii ......text...... .. insertsbeforeit.Observethatifnolinenumberis given,iinsertsbeforelinedot,whileaappends afterlinedot. Movingtextaround:the‘‘m’’command Themovecommandmisusedforcuttingand pasting−itletsyoumoveagroupoflinesfrom oneplacetoanotherinthebuffer.Supposeyou wanttoputthefirstthreelinesofthebufferatthe endinstead.Youcoulddoitbysaying: 11,,33wwtteemmpp $$rrtteemmpp 11,,33dd (Doyouseewhy?)butyoucandoitaloteasier withthemcommand: 11,,33mm$$ Thegeneralcaseis startline,endlinemmafterthisline Noticethatthereisathirdlinetobespecified− theplacewherethemovedstuffgetsput.Of coursethelinestobemovedcanbespecifiedby contextsearches;ifyouhad FFiirrssttppaarraaggrraapphh ...... eennddoofffifirrssttppaarraaggrraapphh.. SSeeccoonnddppaarraaggrraapphh ...... eennddooffsseeccoonnddppaarraaggrraapphh.. youcouldreversethetwoparagraphslikethis: //SSeeccoonndd//,,//eennddooffsseeccoonndd//mm//FFiirrsstt//−−11 Noticethe−1:themovedtextgoesaftertheline mentioned.Dotgetssettothelastlinemoved. Theglobalcommands‘‘g’’and‘‘v’’ Theglobalcommandgisusedtoexecuteone ormoreedcommandsonallthoselinesinthe bufferthatmatchsomespecifiedstring.Forexample gg//ppeelliinngg//pp printsalllinesthatcontainpeling.Moreusefully, gg//ppeelliinngg//ss////ppeelllliinngg//ggpp makesthesubstitutioneverywhereontheline, thenprintseachcorrectedline.Comparethisto 11,,$$ss//ppeelliinngg//ppeelllliinngg//ggpp whichonlyprintsthelastlinesubstituted. Anothersubtledifferenceisthatthegcommand doesnotgivea?ifpelingisnotfoundwherethe scommandwill. Theremaybeseveralcommands(includinga, c,i,r,w,butnotg);inthatcase,everyline exceptthelastmustendwithabackslash\: gg//xxxxxx//..−−11ss//aabbcc//ddeeff//\\ ..++22ss//gghhii//jjkkll//\\ ..−−22,,..pp makeschangesinthelinesbeforeandaftereach linethatcontainsxxx,thenprintsallthreelines. Thevcommandisthesameasg,exceptthat thecommandsareexecutedoneverylinethat doesnotmatchthestringfollowingv: vv////dd deleteseverylinethatdoesnotcontainablank. SpecialCharacters Youmayhavenoticedthatthingsjustdon’t workrightwhenyouusedsomecharacterslike.,∗, $,andothersincontextsearchesandthesubstitutecommand.Thereasonisrathercomplex, althoughthecureissimple.Basically,edtreats thesecharactersasspecial,withspecialmeanings. Forinstance,inacontextsearchorthefirststring ofthesubstitutecommandonly,.means‘‘any character,’’notaperiod,so −−99−− //xx..yy// means‘‘alinewithanx,anycharacter,anday,’’ notjust‘‘alinewithanx,aperiod,anday.’’A completelistofthespecialcharactersthatcan causetroubleisthefollowing: ˆˆ ..$$[[∗∗\\ Warning:Thebackslashcharacter\isspecialto ed.Forsafety’ssake,avoiditwherepossible.If youhavetouseoneofthespecialcharactersina substitutecommand,youcanturnoffitsmagic meaningtemporarilybyprecedingitwiththe backslash.Thus ss//\\\\\\..\\∗∗//bbaacckkssllaasshhddoottssttaarr// willchange\.∗into‘‘backslashdotstar’’. Hereisahurriedsynopsisoftheotherspecial characters.First,thecircumflexˆ signifiesthe beginningofaline.Thus //ˆ ˆ ssttrriinngg// findsstringonlyifitisatthebeginningofaline: itwillfind ssttrriinngg butnot tthheessttrriinngg...... Thedollar-sign$isjusttheoppositeofthecir-cumflex;itmeanstheendofaline: //ssttrriinngg$$// willonlyfindanoccurrenceofstringthatisat theendofsomeline.Thisimplies,ofcourse,that //ˆ ˆ ssttrriinngg$$// willfindonlyalinethatcontainsjuststring,and //ˆ ˆ ..$$// findsalinecontainingexactlyonecharacter. Thecharacter.,aswementionedabove, matchesanything; //xx..yy// matchesanyof xx++yy xx−−yy xxyy xx..yy Thisisusefulinconjunctionwith∗,whichisa repetitioncharacter;a∗isashorthandfor‘‘any numberofa’s,’’so.∗matchesanynumberofanythings.Thisisusedlikethis: ss//..∗∗//ssttuuffff// whichchangesanentireline,or ss//..∗∗,,//// whichdeletesallcharactersinthelineuptoand includingthelastcomma.(Since.∗findsthe longestpossiblematch,thisgoesuptothelast comma.) [isusedwith]toform‘‘characterclasses’’;for example, //[[00112233445566778899]]// matchesanysingledigit−anyoneofthecharactersinsidethebraceswillcauseamatch.Thiscan beabbreviatedto[0−9]. Finally,the&isanothershorthandcharacter −itisusedonlyontheright-handpartofasub-stitutecommandwhereitmeans‘‘whateverwas matchedontheleft-handside’’.Itisusedtosave typing.Supposethecurrentlinecontained NNoowwiisstthheettiimmee andyouwantedtoputparenthesesaroundit.You couldjustretypetheline,butthisistedious.Or youcouldsay ss//ˆ ˆ //((// ss//$$//))// usingyourknowledgeofˆ and$.Buttheeasiest wayusesthe&: ss//..∗∗//((&&))// Thissays‘‘matchthewholeline,andreplaceitby itselfsurroundedbyparentheses.’’The&canbe usedseveraltimesinaline;considerusing ss//..∗∗//&&??&&!!!!// toproduce NNoowwiisstthheettiimmee??NNoowwiisstthheettiimmee!!!! Youdon’thavetomatchthewholeline,of course:ifthebuffercontains tthheeeennddoofftthheewwoorrlldd youcouldtype //wwoorrlldd//ss////&&iissaatthhaanndd// toproduce tthheeeennddoofftthheewwoorrllddiissaatthhaanndd Observethisexpressioncarefully,foritillustrates howtotakeadvantageofedtosavetyping.The string/world/foundthedesiredline;theshorthand//foundthesamewordintheline;andthe &savesyoufromtypingitagain. The&isaspecialcharacteronlywithinthe replacementtextofasubstitutecommand,and hasnospecialmeaningelsewhere.Youcanturn offthespecialmeaningof&byprecedingitwitha \:

-10-ss//aammppeerrssaanndd//\\&&// willconverttheword‘‘ampersand’’intotheliteral symbol&inthecurrentline. SummaryofCommandsandLineNumbers Thegeneralformofedcommandsisthecommandname,perhapsprecededbyoneortwoline numbers,and,inthecaseofe,r,andw,followed byafilename.Onlyonecommandisallowedper line,butapcommandmayfollowanyothercommand(exceptfore,r,wandq). a:Append,thatis,addlinestothebuffer(atline dot,unlessadifferentlineisspecified).Appending continuesuntil.istypedonanewline.Dotisset tothelastlineappended. c:Changethespecifiedlinestothenewtextwhich follows.Thenewlinesareterminatedbya.,as witha.Ifnolinesarespecified,replacelinedot. Dotissettolastlinechanged. d:Deletethelinesspecified.Ifnonearespecified, deletelinedot.Dotissettothefirstundeleted line,unless$isdeleted,inwhichcasedotissetto $. e:Editnewfile.Anypreviouscontentsofthe bufferarethrownaway,soissueawbeforehand. f:Printrememberedfilename.Ifanamefollowsf therememberednamewillbesettoit. g:Thecommand gg//------//ccoommmmaannddss willexecutethecommandsonthoselinesthatcontain---,whichcanbeanycontextsearchexpres-sion. i:Insertlinesbeforespecifiedline(ordot)untila. istypedonanewline.Dotissettolastline inserted. m:Movelinesspecifiedtoafterthelinenamed afterm.Dotissettothelastlinemoved. p:Printspecifiedlines.Ifnonespecified,print linedot.Asinglelinenumberisequivalentto line-numberp.Asinglereturnprints.+1,the nextline. q:Quited.Wipesoutalltextinbufferifyougive ittwiceinarowwithoutfirstgivingawcommand. r:Readafileintobuffer(atendunlessspecified elsewhere.)Dotsettolastlineread. s:Thecommand ss//ssttrriinngg11//ssttrriinngg22// substitutesthecharactersstring1intostring2in thespecifiedlines.Ifnolinesarespecified,make thesubstitutioninlinedot.Dotissettolastline inwhichasubstitutiontookplace,whichmeans thatifnosubstitutiontookplace,dotisnot changed.schangesonlythefirstoccurrenceof string1onaline;tochangeallofthem,typeag afterthefinalslash. v:Thecommand vv//------//ccoommmmaannddss executescommandsonthoselinesthatdonot contain---. w:Writeoutbufferontoafile.Dotisnot changed. .=:Printvalueofdot.(=byitselfprintsthe valueof$.) !:Theline !!ccoommmmaanndd--lliinnee causescommand-linetobeexecutedasaUNIX command. /-----/:Contextsearch.Searchfornextline whichcontainsthisstringofcharacters.Printit. Dotissettothelinewherestringwasfound. Searchstartsat.+1,wrapsaroundfrom$to1, andcontinuestodot,ifnecessary. ?-----?:Contextsearchinreversedirection.Start searchat.−1,scanto1,wraparoundto$.