Edit:ATutorial RickiBlau JamesJoyce ComputingServices UniversityofCalifornia Berkeley,California94720 ABSTRACT Thisnarrativeintroductiontotheuseofthetexteditoreditassumesnoprior familiaritywithcomputersorwithtextediting.Itsaimistoleadthebeginning UNIX†userthroughthefundamentalstepsofwritingandrevisingafileoftext. Edit,aversionofthetexteditorex,wasdesignedtoprovideaninformativeenvironmentfornewandcasualusers. WewelcomecommentsandsuggestionsaboutthistutorialandtheUNIX documentationingeneral. September1981 †UNIXisatrademarkofBellLaboratories.

-2-Contents Introduction3 Session14 MakingcontactwithUNIX4 Loggingin4 Askingforedit4 The‘‘Commandnotfound’’message5 Asummary5 Enteringtext5 Messagesfromedit5 Textinputmode6 Makingcorrections6 Writingtexttodisk7 Signingoff7 Session28 Addingmoretexttothefile8 Interrupt8 Makingcorrections8 Listingwhat’sinthebuffer(p)9 Findingthingsinthebuffer9 Thecurrentline10 Numberinglines(nu)10 Substitutecommand(s)10 Anotherwaytolistwhat’sinthebuffer(z)11 Savingthemodifiedtext12 Session313 Bringingtextintothebuffer(e)13 Movingtextinthebuffer(m)13 Copyinglines(copy)14 Deletinglines(d)14 Awordortwoofcaution15 Undo(u)totherescue15 Moreaboutthedot(.)andbufferend($)16 Movingaroundinthebuffer(+and−)16 Changinglines(c)17 Session418 Makingcommandsglobal(g)18 Moreaboutsearchingandsubstituting19 Specialcharacters19 IssuingUNIXcommandsfromtheeditor20 Filenamesandfilemanipulation20 Thefile(f)command20 Readingadditionalfiles(r)21 Writingpartsofthebuffer21 Recoveringfiles21 Otherrecoverytechniques21 Furtherreadingandotherinformation22 Usingex22 Index23 -3-Introduction Texteditingusingaterminalconnectedtoacomputerallowsyoutocreate,modify,and printtexteasily.Atexteditorisaprogramthatassistsyouasyoucreateandmodifytext.The texteditoryouwilllearnhereisnamededit.Creatingtextusingeditisaseasyastypingitonan electrictypewriter.Modifyingtextinvolvestellingthetexteditorwhatyouwanttoadd,change, ordelete.Youcanreviewyourtextbytypingacommandtoprintthefilecontentsastheywere enteredbyyou.Anotherprogram,atextformatter,rearrangesyourtextforyouinto‘‘finished form.’’Thisdocumentdoesnotdiscusstheuseofatextformatter. Theselessonsassumenopriorfamiliaritywithcomputersorwithtextediting.Theyconsist ofaseriesoftexteditingsessionswhichleadyouthroughthefundamentalstepsofcreatingand revisingtext.Afterscanningeachlessonandbeforebeginningthenext,youshouldpracticethe examplesataterminaltogetafeelingfortheactualprocessoftextediting.Ifyousetasidesome timeforexperimentation,youwillsoonbecomefamiliarwithusingthecomputertowriteand modifytext.Inadditiontotheactualuseofthetexteditor,otherfeaturesofUNIXwillbevery importanttoyourwork.Youcanbegintolearnabouttheseotherfeaturesbyreading‘‘CommunicatingwithUNIX’’oroneoftheothertutorialsthatprovideageneralintroductiontothesystem.Youwillbereadytoproceedwiththislessonassoonasyouarefamiliarwith(1)yourterminalanditsspecialkeys,(2)theloginprocedure,(3)andthewaysofcorrectingtypingerrors. Let’sfirstdefinesometerms: programAsetofinstructions,giventothecomputer,describingthesequenceofstepsthe computerperformsinordertoaccomplishaspecifictask.Thetasksmustbespecific,suchasbalancingyourcheckbookoreditingyourtext.Ageneraltask,suchas workingforworldpeace,issomethingwecando,butnotsomethingwecanwrite programstodo. UNIXUNIXisaspecialtypeofprogram,calledanoperatingsystem,thatsupervisesthe machineryandallotherprogramscomprisingthetotalcomputersystem. editeditisthenameoftheUNIXtexteditoryouwillbelearningtouse,andisaprogram thataidsyouinwritingorrevisingtext.Editwasdesignedforbeginningusers,and isasimplifiedversionofaneditornamedex. fileEachUNIXaccountisallottedspaceforthepermanentstorageofinformation,such asprograms,dataortext.Afileisalogicalunitofdata,forexample,anessay,a program,orachapterfromabook,whichisstoredonacomputersystem.Once youcreateafile,itiskeptuntilyouinstructthesystemtoremoveit.YoumaycreateafileduringoneUNIXsession,endthesession,andreturntouseitatalater time.Filescontainanythingyouchoosetowriteandstoreinthem.Thesizesof filesvarytosuityourneeds;onefilemightholdonlyasinglenumber,yetanother mightcontainaverylongdocumentorprogram.Theonlywaytosaveinformation fromonesessiontothenextistostoreitinafile,whichyouwilllearninSession1. filenameFilenamesareusedtodistinguishonefilefromanother,servingthesamepurposeas thelabelsofmanilafoldersinafilecabinet.Inordertowriteoraccessinformation inafile,youusethenameofthatfileinaUNIXcommand,andthesystemwillautomaticallylocatethefile. diskFilesarestoredonaninput/outputdevicecalledadisk,whichlookssomethinglike astackofphonographrecords.Eachsurfaceiscoatedwithamaterialsimilartothe coatingonmagneticrecordingtape,andinformationisrecordedonit. bufferAtemporaryworkspace,madeavailabletotheuserforthedurationofasessionof texteditingandusedforcreatingandmodifyingthetextfile.Wecanthinkofthe bufferasablackboardthatiserasedaftereachclass,whereeachsessionwiththe editorisaclass.

-4-Session1 MakingcontactwithUNIX TousetheeditoryoumustfirstmakecontactwiththecomputerbyloggingintoUNIX. We’llquicklyreviewthestandardUNIXloginprocedureforthetwowaysyoucanmakecontact:on aterminalthatisdirectlylinkedtothecomputer,oroveratelephonelinewherethecomputer answersyourcall. Directly-linkedterminals TurnonyourterminalandpresstheRETURNkey.Youarenowreadytologin. Dial-upterminals Ifyourterminalconnectswiththecomputeroveratelephoneline,turnontheterminal,dial thesystemaccessnumber,and,whenyouhearahigh-pitchedtone,placethereceiverofthetele-phoneintheacousticcoupler.Youarenowreadytologin. Loggingin Themessageinvitingyoutologinis: :login: Typeyourloginname,whichidentifiesyoutoUNIX,onthesamelineastheloginmessage,and pressRETURN.Iftheterminalyouareusinghasbothupperandlowercase,besureyouenter yourloginnameinlowercase;otherwiseUNIXassumesyourterminalhasonlyuppercaseand willnotrecognizelowercaselettersyoumaytype.UNIXtypes‘‘:login:’’andyoureplywithyour loginname,forexample‘‘susan’’: :login:susan(andpresstheRETURNkey) (Intheexamples,inputyouwouldtypeappearsinboldfacetodistinguishitfromtheresponses fromUNIX.) UNIXwillnextrespondwitharequestforapasswordasanadditionalprecautiontoprevent unauthorizedpeoplefromusingyouraccount.Thepasswordwillnotappearwhenyoutypeit,to preventothersfromseeingit.Themessageis: Password:(typeyourpasswordandpressRETURN) Ifanyoftheinformationyougaveduringtheloginsequencewasmistypedorincorrect,UNIXwill respondwith Loginincorrect. :login: inwhichcaseyoushouldstarttheloginprocessanew.Assumingthatyouhavesuccessfully loggedin,UNIXwillprintthemessageofthedayandeventuallywillpresentyouwitha%atthe beginningofafreshline.The%istheUNIXpromptsymbolwhichtellsyouthatUNIXisreadyto acceptacommand. Askingforeeddiitt YouarereadytotellUNIXthatyouwanttoworkwithedit,thetexteditor.Nowisaconvenienttimetochooseanameforthefileoftextyouareabouttocreate.Tobeginyourediting session,typeeditfollowedbyaspaceandthenthefilenameyouhaveselected;forexample, ‘‘text’’.Whenyouhavecompletedthecommand,presstheRETURNkeyandwaitforedit’s response:

-5- %edittext(followedbyaRETURN) "text"Nosuchfileordirectory : Ifyoutypedthecommandcorrectly,youwillnowbeincommunicationwithedit.Edithasset asideabufferforuseasatemporaryworkingspaceduringyourcurrenteditingsession.Italso checkedtoseeifthefileyounamed,‘‘text’’,alreadyexisted.Itwasunabletofindsuchafile, since‘‘text’’isanewfileweareabouttocreate.Editconfirmsthiswiththeline: "text"Nosuchfileordirectory Onthenextlineappearsedit’sprompt‘‘:’’,announcingthatyouareincommandmodeandedit expectsacommandfromyou.Youmaynowbegintocreatethenewfile. The‘‘Commandnotfound’’message Ifyoumisspellededitbytyping,say,‘‘editor’’,yourrequestwouldbehandledasfollows: %editor editor:Commandnotfound % Yourmistakeincallingedit‘‘editor’’wastreatedbyUNIXasarequestforaprogramnamed‘‘editor’’.Sincethereisnoprogramnamed‘‘editor’’,UNIXreportedthattheprogramwas‘‘notfound’’. Anew%indicatesthatUNIXisreadyforanothercommand,andyoumaythenenterthecorrect command. Asummary YourexchangewithUNIXasyouloggedinandmadecontactwitheditshouldlooksomethinglikethis: :login:susan Password: ...AMessageofGeneralInterest... %edittext "text"Nosuchfileordirectory : Enteringtext Youmaynowbeginenteringtextintothebuffer.Thisisdonebyappending(oradding) texttowhateveriscurrentlyinthebuffer.Sincethereisnothinginthebufferatthemoment, youareappendingtexttonothing;ineffect,sinceyouareaddingtexttonothingyouarecreating text.Mosteditcommandshavetwoforms:awordthatsuggestswhatthecommanddoes,anda shorterabbreviationofthatword.Eitherformmaybeused.Manybeginnersfindthefullcommandnameseasiertorememberatfirst,butonceyouarefamiliarwitheditingyoumaypreferto typetheshorterabbreviations.Thecommandtoinputtextis‘‘append’’,anditmaybeabbreviated‘‘a’’.TypeappendandpresstheRETURNkey. %edittext :append Messagesfromeeddiitt Ifyoumakeamistakeinenteringacommandandtypesomethingthateditdoesnotrecognize,editwillrespondwithamessageintendedtohelpyoudiagnoseyourerror.Forexample,if youmisspellthecommandtoinputtextbytyping,perhaps,‘‘add’’insteadof‘‘append’’or‘‘a’’, youwillreceivethismessage:

-6- :add add:Notaneditorcommand : Whenyoureceiveadiagnosticmessage,checkwhatyoutypedinordertodeterminewhatpartof yourcommandconfusededit.Themessageabovemeansthateditwasunabletorecognizeyour mistypedcommandand,therefore,didnotexecuteit.Instead,anew‘‘:’’appearedtoletyou knowthateditisagainreadytoexecuteacommand. Textinputmode Bygivingthecommand‘‘append’’(orusingtheabbreviation‘‘a’’),youenteredtextinput mode,alsoknownasappendmode.Whenyouentertextinputmode,editstopssendingyoua prompt.Youwillnotreceiveanypromptsorerrormessageswhileintextinputmode.Youcan enterprettymuchanythingyouwantonthelines.Thelinesaretransmittedonebyonetothe bufferandheldthereduringtheeditingsession.Youmayappendasmuchtextasyouwant,and whenyouwishtostopenteringtextlinesyoushouldtypeaperiodastheonlycharacterontheline andpresstheRETURNkey.WhenyoutypetheperiodandpressRETURN,yousignalthatyou wanttostopappendingtext,andeditrespondsbyallowingyoutoexittextinputmodeandreentercommandmode.Editwillagainpromptyouforacommandbyprinting‘‘:’’. Leavingappendmodedoesnotdestroythetextinthebuffer.Youhavetoleaveappend modetodoanyoftheotherkindsofediting,suchaschanging,adding,orprintingtext.Ifyou typeaperiodasthefirstcharacterandtypeanyothercharacteronthesameline,editwillbelieve youwanttoremaininappendmodeandwillnotletyouout.Asthiscanbeveryfrustrating,be suretotypeonlytheperiodandtheRETURNkey. Thisisagoodplacetolearnanimportantlessonaboutcomputersandtext:ablankspace isacharacterasfarasacomputerisconcerned.Ifyousomuchastypeaperiodfollowedbya blank(thatis,typeaperiodandthenthespacebaronthekeyboard),youwillremaininappend modewiththelastlineoftextbeing: . Let’ssaythatthelinesoftextyouenterare(trytotypeexactlywhatyousee,including‘‘thiss’’): Thisissomesampletext. Andthississomemoretext. Texteditingisstrange,butnice. . ThelastlineistheperiodfollowedbyaRETURNthatgetsyououtofappendmode. Makingcorrections IfyouhavereadageneralintroductiontoUNIX,suchas‘‘CommunicatingwithUNIX’’,you willrecallthatitispossibletoeraseindividuallettersthatyouhavetyped.Thisisdonebytypingthedesignatederasecharacterasmanytimesastherearecharactersyouwanttoerase. Theusualerasecharacteristhebackspace(control-H),andyoucancorrecttypingerrorsin thelineyouaretypingbyholdingdowntheCTRLkeyandtypingthe‘‘H’’key.Ifyoutrytyping control-Hyouwillnoticethattheterminalbackspacesinthelineyouareon.Youcanbackspace overyourerror,andthentypewhatyouwanttobetherestoftheline. Ifyoumakeabadstartinalineandwouldliketobeginagain,youcaneitherbackspaceto thebeginningofthelineoryoucanusetheat-sign‘‘@’’toeraseeverythingontheline: Textedtiingisstrange,but@ Texteditingisstrange,butnice. Whenyoutypetheat-sign(@),youerasetheentirelinetypedsofarandaregivenafreshlineto typeon.Youmayimmediatelybegintoretypetheline.This,unfortunately,doesnothelpafter -7-youtypethelineandpressRETURN.Tomakecorrectionsinlinesthathavebeencompleted,itis necessarytousetheeditingcommandscoveredinthenextsessionandthosethatfollow. Writingtexttodisk Youarenowreadytoeditthetext.Thesimplestkindofeditingistowriteittodiskasa fileforsafekeepingafterthesessionisover.Thisistheonlywaytosaveinformationfromonesessiontothenext,sincetheeditor’sbufferistemporaryandwilllastonlyuntiltheendoftheeditingsession.Learninghowtowriteafiletodiskissecondinimportanceonlytoenteringthetext. Towritethecontentsofthebuffertoadiskfile,usethecommand‘‘write’’(oritsabbreviation ‘‘w’’): :write Editwillcopythecontentsofthebuffertoadiskfile.Ifthefiledoesnotyetexist,anewfilewill becreatedautomaticallyandthepresenceofa‘‘[Newfile]’’willbenoted.Thenewly-createdfile willbegiventhenamespecifiedwhenyouenteredtheeditor,inthiscase‘‘text’’.Toconfirmthat thediskfilehasbeensuccessfullywritten,editwillrepeatthefilenameandgivethenumberof linesandthetotalnumberofcharactersinthefile.Thebufferremainsunchangedbythe‘‘write’’ command.Allofthelinesthatwerewrittentodiskwillstillbeinthebuffer,shouldyouwantto modifyoraddtothem. Editmusthaveafilenametousebeforeitcanwriteafile.Ifyouforgottoindicatethe nameofthefilewhenyoubegantheeditingsession,editwillprint Nocurrentfilename inresponsetoyourwritecommand.Ifthishappens,youcanspecifythefilenameinanewwrite command: :writetext Afterthe‘‘write’’(or‘‘w’’),typeaspaceandthenthenameofthefile. Signingoff WehavedoneenoughforthisfirstlessononusingtheUNIXtexteditor,andarereadyto quitthesessionwithedit.Todothiswetype‘‘quit’’(or‘‘q’’)andpressRETURN: :write "text"[Newfile]3lines,90characters :quit % The%isfromUNIXtotellyouthatyoursessionwitheditisoverandyoumaycommandUNIX further.Sincewewanttoendtheentiresessionattheterminal,wealsoneedtoexitfromUNIX. InresponsetotheUNIXpromptof‘‘%’’typethecommand %logout ThiswillendyoursessionwithUNIX,andwillreadytheterminalforthenextuser.Itisalways importanttotypelogoutattheendofasessiontomakeabsolutelysurenoonecouldaccidentallystumbleintoyourabandonedsessionandthusgainaccesstoyourfiles,temptingeventhe mosthonestofsouls. ThisistheendofthefirstsessiononUNIXtextediting.

-8-Session2 LoginwithUNIXasinthefirstsession: :login:susan(carriagereturn) Password:(givepasswordandcarriagereturn) ...AMessageofGeneralInterest... % Whenyouindicateyouwanttoedit,youcanspecifythenameofthefileyouworkedonlasttime. Thiswillstarteditworking,anditwillfetchthecontentsofthefileintothebuffer,sothatyou canresumeeditingthesamefile.Whenedithascopiedthefileintothebuffer,itwillrepeatits nameandtellyouthenumberoflinesandcharactersitcontains.Thus, %edittext "text"3lines,90characters : meansyouaskededittofetchthefilenamed‘‘text’’forediting,causingittocopythe90charactersoftextintothebuffer.Editawaitsyourfurtherinstructions,andindicatesthisbyitsprompt character,thecolon(:).Inthissession,wewillappendmoretexttoourfile,printthecontentsof thebuffer,andlearntochangethetextofaline. Addingmoretexttothefile Ifyouwanttoaddmoretotheendofyourtextyoumaydosobyusingtheappendcommandtoentertextinputmode.When‘‘append’’isthefirstcommandofyoureditingsession,the linesyouenterareplacedattheendofthebuffer.Herewe’llusetheabbreviationfortheappend command,‘‘a’’: :a ThisistextaddedinSession2. Itdoesn’tmeanmuchhere,but itdoesillustratetheeditor. . Youmayrecallthatonceyouenterappendmodeusingthe‘‘a’’(or‘‘append’’)command,youneed totypealinecontainingonlyaperiod(.)toexitappendmode. Interrupt ShouldyoupresstheRUBkey(sometimeslabelledDELETE)whileworkingwithedit,itwill sendthismessagetoyou: Interrupt : Anycommandthateditmightbeexecutingisterminatedbyrubordelete,causingedittoprompt youforanewcommand.Ifyouareappendingtextatthetime,youwillexitfromappendmode andbeexpectedtogiveanothercommand.Thelineoftextyouweretypingwhentheappend commandwasinterruptedwillnotbeenteredintothebuffer. Makingcorrections Ifwhiletypingthelineyouhitanincorrectkey,recallthatyoumaydeletetheincorrect characterorcanceltheentirelineofinputbyerasingintheusualway.Refereithertothelast fewpagesofSession1orto‘‘CommunicatingwithUNIX’’ifyouneedtoreviewtheproceduresfor makingacorrection.ThemostimportantideatorememberisthaterasingacharacterorcancellingalinemustbedonebeforeyoupresstheRETURNkey.

-9-Listingwhat’sinthebuffer(p) HavingappendedtexttowhatyouwroteinSession1,youmightwanttoseeallthelinesin thebuffer.Toprintthecontentsofthebuffer,typethecommand: :1,$p The‘‘1’’†standsforline1ofthebuffer,the‘‘$’’isaspecialsymboldesignatingthelastlineofthe buffer,and‘‘p’’(orprint)isthecommandtoprintfromline1totheendofthebuffer.Thecommand‘‘1,$p’’givesyou: Thisissomesampletext. Andthississomemoretext. Texteditingisstrange,butnice. ThisistextaddedinSession2. Itdoesn’tmeanmuchhere,but itdoesillustratetheeditor. Occasionally,youmayaccidentallytypeacharacterthatcan’tbeprinted,whichcanbedoneby strikingakeywhiletheCTRLkeyispressed.Inprintinglines,editusesaspecialnotationtoshow theexistenceofnon-printingcharacters.Supposeyouhadintroducedthenon-printingcharacter ‘‘control-A’’intotheword‘‘illustrate’’byaccidentlypressingtheCTRLkeywhiletyping‘‘a’’.This canhappenonmanyterminalsbecausetheCTRLkeyandthe‘‘A’’keyarebesideeachother.If yourfingerpressesbetweenthetwokeys,control-Aresults.Whenaskedtoprintthecontentsof thebuffer,editwoulddisplay itdoesillustrˆ Atetheeditor. Torepresentthecontrol-A,editshows‘‘ˆ A’’.Thesequence‘‘ˆ ’’followedbyacapitalletterstands fortheonecharacterenteredbyholdingdowntheCTRLkeyandtypingtheletterwhichappears afterthe‘‘ˆ ’’.We’llsoondiscussthecommandsthatcanbeusedtocorrectthistypingerror. Inlookingoverthetextweseethat‘‘this’’istypedas‘‘thiss’’inthesecondline,adeliberate errorsowecanlearntomakecorrections.Let’scorrectthespelling. Findingthingsinthebuffer Inordertochangesomethinginthebufferwefirstneedtofindit.Wecanfind‘‘thiss’’in thetextwehaveenteredbylookingatalistingofthelines.Physicallyspeaking,wesearchthe linesoftextlookingfor‘‘thiss’’andstopsearchingwhenwehavefoundit.Thewaytotelleditto searchforsomethingistotypeitinsideslashmarks: :/thiss/ Bytyping/thiss/andpressingRETURN,youinstructedittosearchfor‘‘thiss’’.Ifyouaskedit tolookforapatternofcharacterswhichitcannotfindinthebuffer,itwillrespond‘‘Patternnot found’’.Wheneditfindsthecharacters‘‘thiss’’,itwillprintthelineoftextforyourinspection: Andthississomemoretext. Editisnowpositionedinthebufferatthelineitjustprinted,readytomakeachangeintheline. †Thenumeral‘‘one’’isthetopleft-mostkey,andshouldnotbeconfusedwiththeletter‘‘el’’.

-10-Thecurrentline Editkeepstrackofthelineinthebufferwhereitislocatedatalltimesduringanediting session.Ingeneral,thelinethathasbeenmostrecentlyprinted,entered,orchangedisthecurrentlocationinthebuffer.Theeditorispreparedtomakechangesatthecurrentlocationinthe buffer,unlessyoudirectittoanotherlocation. Inparticular,whenyoubringafileintothebuffer,youwillbelocatedatthelastlineinthe file,wheretheeditorleftoffcopyingthelinesfromthefiletothebuffer.Ifyourfirsteditingcommandis‘‘append’’,thelinesyouenterareaddedtotheendofthefile,afterthecurrentline—the lastlineinthefile. Youcanrefertoyourcurrentlocationinthebufferbythesymbolperiod(.)usuallyknown bythename‘‘dot’’.Ifyoutype‘‘.’’andcarriagereturnyouwillbeinstructingedittoprintthe currentline: :. Andthississomemoretext. Ifyouwanttoknowthenumberofthecurrentline,youcantype.=andpressRETURN,and editwillrespondwiththelinenumber: :.= 2 IfyoutypethenumberofanylineandpressRETURN,editwillpositionyouatthatlineandprint itscontents: :2 Andthississomemoretext. Youshouldexperimentwiththesecommandstogainexperienceinusingthemtomakechanges. Numberinglines(nu) Thenumber(nu)commandissimilartoprint,givingboththenumberandthetextof eachprintedline.Toseethenumberandthetextofthecurrentlinetype :nu 2Andthississomemoretext. Notethattheshortestabbreviationforthenumbercommandis‘‘nu’’(andnot‘‘n’’,whichisused foradifferentcommand).Youmayspecifyarangeoflinestobelistedbythenumbercommand inthesamewaythatlinesarespecifiedforprint.Forexample,1,$nulistsalllinesinthebuffer withtheircorrespondinglinenumbers. Substitutecommand(s) Nowthatyouhavefoundthemisspelledword,youcanchangeitfrom‘‘thiss’’to‘‘this’’.As faraseditisconcerned,changingthingsisamatterofsubstitutingonethingforanother.Asa stoodforappend,sosstandsforsubstitute.Wewillusetheabbreviation‘‘s’’toreducethechance ofmistypingthesubstitutecommand.Thiscommandwillinstructedittomakethechange: 2s/thiss/this/ Wefirstindicatethelinetobechanged,line2,andthentypean‘‘s’’toindicatewewanteditto makeasubstitution.Insidethefirstsetofslashesarethecharactersthatwewanttochange,followedbythecharacterstoreplacethem,andthenaclosingslashmark.Tosummarize: 2s/whatistobechanged/whattochangeitto/ Ifeditfindsanexactmatchofthecharacterstobechangeditwillmakethechangeonlyinthe firstoccurrenceofthecharacters.Ifitdoesnotfindthecharacterstobechanged,itwillrespond:

-11-Substitutepatternmatchfailed indicatingthatyourinstructionscouldnotbecarriedout.Wheneditdoesfindthecharacters thatyouwanttochange,itwillmakethesubstitutionandautomaticallyprintthechangedline, sothatyoucancheckthatthecorrectsubstitutionwasmade.Intheexample, :2s/thiss/this/ Andthisissomemoretext. line2(andline2only)willbesearchedforthecharacters‘‘thiss’’,andwhenthefirstexactmatch isfound,‘‘thiss’’willbechangedto‘‘this’’.Strictlyspeaking,itwasnotnecessaryabovetospecify thenumberofthelinetobechanged.In :s/thiss/this/ editwillassumethatwemeantochangethelinewherewearecurrentlylocated(‘‘.’’).Inthis case,thecommandwithoutalinenumberwouldhaveproducedthesameresultbecausewewere alreadylocatedatthelinewewishedtochange. Foranotherillustrationofthesubstitutecommand,letuschoosetheline: Texteditingisstrange,butnice. Youcanmakethislineabitmorepositivebytakingoutthecharacters‘‘strange,but’’sotheline reads: Texteditingisnice. Acommandthatwillfirstpositioneditatthedesiredlineandthenmakethesubstitutionis: :/strange/s/strange,but// Whatwehavedonehereiscombineoursearchwithoursubstitution.Suchcombinationsareperfectlylegal,andspeedupeditingquiteabitonceyougetusedtothem.Thatis,youdonotnecessarilyhavetouselinenumberstoidentifyalinetoedit.Instead,youmayidentifythelineyou wanttochangebyaskingedittosearchforaspecifiedpatternoflettersthatoccursinthatline. Thepartsoftheabovecommandare: /strange/tellsedittofindthecharacters‘‘strange’’inthetext stellsedittomakeasubstitution /strange,but//substitutesnothingatallforthecharacters‘‘strange,but’’ Youshouldnotethespaceafter‘‘but’’in‘‘/strange,but/’’.Ifyoudonotindicatethatthe spaceistobetakenout,yourlinewillread: Texteditingisnice. whichlooksalittlefunnybecauseoftheextraspacebetween‘‘is’’and‘‘nice’’.Again,werealize fromthisthatablankspaceisarealcharactertoacomputer,andineditingtextweneedtobe awareofspaceswithinalinejustaswewouldbeawareofan‘‘a’’ora‘‘4’’. Anotherwaytolistwhat’sinthebuffer(z) Althoughtheprintcommandisusefulforlookingatspecificlinesinthebuffer,othercommandsmaybemoreconvenientforviewinglargesectionsoftext.Youcanasktoseeascreenfull oftextatatimebyusingthecommandz.Ifyoutype :1z editwillstartwithline1andcontinueprintinglines,stoppingeitherwhenthescreenofyourterminalisfullorwhenthelastlineinthebufferhasbeenprinted.Ifyouwanttoreadthenextsegmentoftext,typethecommand -12- :z Ifnostartinglinenumberisgivenforthezcommand,printingwillstartatthe‘‘current’’line,in thiscasethelastlineprinted.Viewinglinesinthebufferonescreenfullatatimeisknownas paging.Pagingcanalsobeusedtoprintasectionoftextonahard-copyterminal. Savingthemodifiedtext Thisseemstobeagoodplacetopauseinourwork,andsoweshouldendthesecondsession.Ifyou(inhaste)type‘‘q’’toquitthesessionyourdialoguewitheditwillbe: :q Nowritesincelastchange(:quit!overrides) : Thisisedit’swarningthatyouhavenotwrittenthemodifiedcontentsofthebuffertodisk.You runtheriskoflosingtheworkyoudidduringtheeditingsessionsinceyoutypedthelatestwrite command.Becauseinthislessonwehavenotwrittentodiskatall,everythingwehavedone wouldhavebeenlostifedithadobeyedtheqcommand.Ifyoudidnotwanttosavethework doneduringthiseditingsession,youwouldhavetotype‘‘q!’’or(‘‘quit!’’)toconfirmthatyou indeedwantedtoendthesessionimmediately,leavingthefileasitwasafterthemostrecent ‘‘write’’command.However,sinceyouwanttosavewhatyouhaveedited,youneedtotype: :w "text"6lines,171characters andthenfollowwiththecommandstoquitandlogout: :q %logout andhangupthephoneorturnofftheterminalwhenUNIXasksforaname.Terminalsconnected totheportselectorwillstopafterthelogoutcommand,andpressingkeysonthekeyboardwilldo nothing. ThisistheendofthesecondsessiononUNIXtextediting.

-13-Session3 Bringingtextintothebuffer(e) LogintoUNIXandmakecontactwithedit.Youshouldtrytologinwithoutlookingatthe notes,butifyoumustthenbyallmeansdo. Didyouremembertogivethenameofthefileyouwantedtoedit?Thatis,didyoutype %edittext orsimply %edit Bothwaysgetyouincontactwithedit,butthefirstwaywillbringacopyofthefilenamed ‘‘text’’intothebuffer.Ifyoudidforgettotelleditthenameofyourfile,youcangetitintothe bufferbytyping: :etext "text"6lines,171characters Thecommandedit,whichmaybeabbreviatede,tellseditthatyouwanttoeraseanythingthat mightalreadybeinthebufferandbringacopyofthefile‘‘text’’intothebufferforediting.You mayalsousetheedit(e)commandtochangefilesinthemiddleofaneditingsession,ortogive editthenameofanewfilethatyouwanttocreate.Becausetheeditcommandclearsthebuffer, youwillreceiveawarningifyoutrytoeditanewfilewithouthavingsavedacopyoftheoldfile. Thisgivesyouachancetowritethecontentsofthebuffertodiskbeforeeditingthenextfile. Movingtextinthebuffer(m) Editallowsyoutomovelinesoftextfromonelocationinthebuffertoanotherbymeansof themove(m)command.Thefirsttwoexamplesareforillustrationonly,thoughafteryouhave readthisSessionyouarewelcometoreturntothemforpractice.Thecommand :2,4m$ directsedittomovelines2,3,and4totheendofthebuffer($).Theformatforthemovecommandisthatyouspecifythefirstlinetobemoved,thelastlinetobemoved,themovecommand ‘‘m’’,andthelineafterwhichthemovedtextistobeplaced.So, :1,3m6 wouldinstructedittomovelines1through3(inclusive)toalocationafterline6inthebuffer. Tomoveonlyoneline,say,line4,toalocationinthebufferafterline5,thecommandwouldbe ‘‘4m5’’. Let’smovesometextusingthecommand: :5,$m1 2linesmoved itdoesillustratetheeditor. Afterexecutingacommandthatmovesmorethanonelineofthebuffer,edittellshowmanylines wereaffectedbythemoveandprintsthelastmovedlineforyourinspection.Ifyouwanttosee morethanjustthelastline,youcanthenusetheprint(p),z,ornumber(nu)commandtoview moretext.Thebuffershouldnowcontain:

-14-Thisissomesampletext. Itdoesn’tmeanmuchhere,but itdoesillustratetheeditor. Andthisissomemoretext. Texteditingisnice. ThisistextaddedinSession2. Youcanrestoretheoriginalorderbytyping: :4,$m1 or,combiningcontextsearchingandthemovecommand: :/Andthisissome/,/Thisistext/m/Thisissomesample/ (Donottypebothexampleshere!)Theproblemwithcombiningcontextsearchingwiththemove commandisthatyourchanceofmakingatypingerrorinsuchalongcommandisgreaterthanif youtypelinenumbers. Copyinglines(copy) Thecopycommandisusedtomakeasecondcopyofspecifiedlines,leavingtheoriginal lineswheretheywere.Copyhasthesameformatasthemovecommand,forexample: :2,5copy$ makesacopyoflines2through5,placingtheaddedlinesafterthebuffer’send($).Experiment withthecopycommandsothatyoucanbecomefamiliarwithhowitworks.Notethattheshortestabbreviationforcopyisco(andnottheletter‘‘c’’,whichhasanothermeaning). Deletinglines(d) Supposeyouwanttodeletetheline ThisistextaddedinSession2. fromthebuffer.Ifyouknowthenumberofthelinetobedeleted,youcantypethatnumberfollowedbydeleteord.Thisexampledeletesline4,whichis‘‘ThisistextaddedinSession2.’’if youtypedthecommandssuggestedsofar. :4d Itdoesn’tmeanmuchhere,but Here‘‘4’’isthenumberofthelinetobedeleted,and‘‘delete’’or‘‘d’’isthecommandtodeletethe line.Afterexecutingthedeletecommand,editprintsthelinethathasbecomethecurrentline (‘‘.’’). Ifyoudonothappentoknowthelinenumberyoucansearchforthelineandthendeleteit usingthissequenceofcommands: :/addedinSession2./ ThisistextaddedinSession2. :d Itdoesn’tmeanmuchhere,but The‘‘/addedinSession2./’’asksedittolocateandprintthelinecontainingtheindicatedtext, startingitssearchatthecurrentlineandmovinglinebylineuntilitfindsthetext.Onceyouare surethatyouhavecorrectlyspecifiedthelineyouwanttodelete,youcanenterthedelete(d) command.Inthiscaseitisnotnecessarytospecifyalinenumberbeforethe‘‘d’’.Ifnoline numberisgiven,editdeletesthecurrentline(‘‘.’’),thatis,thelinefoundbyoursearch.Afterthe deletion,yourbuffershouldcontain:

-15-Thisissomesampletext. Andthisissomemoretext. Texteditingisnice. Itdoesn’tmeanmuchhere,but itdoesillustratetheeditor. Andthisissomemoretext. Texteditingisnice. ThisistextaddedinSession2. Itdoesn’tmeanmuchhere,but Todeletebothlines2and3: Andthisissomemoretext. Texteditingisnice. youtype :2,3d 2linesdeleted whichspecifiestherangeoflinesfrom2to3,andtheoperationonthoselines—‘‘d’’fordelete. Ifyoudeletemorethanonelineyouwillreceiveamessagetellingyouthenumberoflinesdeleted, asindicatedintheexampleabove. Thepreviousexampleassumesthatyouknowthelinenumbersforthelinestobedeleted. Ifyoudonotyoumightcombinethesearchcommandwiththedeletecommand: :/Andthisissome/,/Texteditingisnice./d Awordortwoofcaution Inusingthesearchfunctiontolocatelinestobedeletedyoushouldbeabsolutelysurethe charactersyougiveasthebasisforthesearchwilltakeedittothelineyouwantdeleted.Edit willsearchforthefirstoccurrenceofthecharactersstartingfromwhereyoulastedited−thatis, fromthelineyouseeprintedifyoutypedot(.). Asearchbasedontoofewcharactersmayresultinthewronglinesbeingdeleted,whichedit willdoaseasilyasifyouhadmeantit.Forthisreason,itisusuallysafertospecifythesearch andthendeleteintwoseparatesteps,atleastuntilyoubecomefamiliarenoughwithusingthe editorthatyouunderstandhowbesttospecifysearches.Forabeginneritisnotabadideato double-checkeachcommandbeforepressingRETURNtosendthecommandonitsway. Undo(u)totherescue Theundo(u)commandhastheabilitytoreversetheeffectsofthelastcommandthat changedthebuffer.Toundothepreviouscommand,type‘‘u’’or‘‘undo’’.Undocanrescuethe contentsofthebufferfrommanyanunfortunatemistake.However,itspowersarenotunlimited, soitisstillwisetobereasonablycarefulaboutthecommandsyougive. Itispossibletoundoonlycommandswhichhavethepowertochangethebuffer—for example,delete,append,move,copy,substitute,andevenundoitself.Thecommandswrite(w) andedit(e),whichinteractwithdiskfiles,cannotbeundone,norcancommandsthatdonot changethebuffer,suchasprint.Mostimportantly,theonlycommandthatcanbereversedby undoisthelast‘‘undo-able’’commandyoutyped.Youcanusecontrol-Hand@tochangecom-mandswhileyouaretypingthem,andundotoreversetheeffectofthecommandsafteryouhave typedthemandpressedRETURN. Toillustrate,let’sissueanundocommand.Recallthatthelastbuffer-changingcommand wegavedeletedthelinesformerlynumbered2and3.Typingundoatthismomentwillreverse theeffectsofthedeletion,causingthosetwolinestobereplacedinthebuffer.

-16- :u 2morelinesinfileafterundo Andthisissomemoretext. Hereagain,editinformsyouifthecommandaffectsmorethanoneline,andprintsthetextofthe linewhichisnow‘‘dot’’(thecurrentline). Moreaboutthedot(.)andbufferend($) Thefunctionassumedbythesymboldotdependsonitscontext.Itcanbeused: 1.toexitfromappendmode;wetypedot(andonlyadot)onalineandpressRETURN; 2.torefertothelineweareatinthebuffer. Dotcanalsobecombinedwiththeequalsigntogetthenumberofthelinecurrentlybeingedited: :.= Ifwetype‘‘.=’’weareaskingforthenumberoftheline,andifwetype‘‘.’’weareaskingforthe textoftheline. Inthiseditingsessionandthelast,weusedthedollarsigntoindicatetheendofthebuffer incommandssuchasprint,copy,andmove.Thedollarsignasacommandasksedittoprintthe lastlineinthebuffer.Ifthedollarsigniscombinedwiththeequalsign($=)editwillprintthe linenumbercorrespondingtothelastlineinthebuffer. ‘‘.’’and‘‘$’’,then,representlinenumbers.Wheneverappropriate,thesesymbolscanbe usedinplaceoflinenumbersincommands.Forexample :.,$d instructsedittodeletealllinesfromthecurrentline(.)totheendofthebuffer. Movingaroundinthebuffer(+and−) Whenyouareeditingyouoftenwanttogobackandre-readapreviousline.Youcould specifyacontextsearchforalineyouwanttoreadifyouremembersomeofitstext,butifyou simplywanttoseewhatwaswrittenafew,say3,linesago,youcantype −3p Thistellsedittomovebacktoaposition3linesbeforethecurrentline(.)andprintthatline. Youcanmoveforwardinthebuffersimilarly: +2p instructsedittoprintthelinethatis2aheadofyourcurrentposition. Youmayuse‘‘+’’and‘‘−’’inanycommandwhereeditacceptslinenumbers.Linenumbers specifiedwith‘‘+’’or‘‘−’’canbecombinedtoprintarangeoflines.Thecommand :−1,+2copy$ makesacopyof4lines:thecurrentline,thelinebeforeit,andthetwoafterit.Thecopiedlines willbeplacedafterthelastlineinthebuffer($),andtheoriginallinesreferredtoby‘‘−1’’and ‘‘+2’’remainwheretheyare. Trytypingonly‘‘−’’;youwillmovebackonelinejustasifyouhadtyped‘‘−1p’’.Typing thecommand‘‘+’’workssimilarly.Youmightalsotrytypingafewplusorminussignsinarow (suchas‘‘+++’’)toseeedit’sresponse.TypingRETURNaloneonalineistheequivalentoftyping‘‘+1p’’;itwillmoveyouonelineaheadinthebufferandprintthatline. Ifyouareatthelastlineofthebufferandtrytomovefurtherahead,perhapsbytypinga ‘‘+’’oracarriagereturnaloneontheline,editwillremindyouthatyouareattheendofthe buffer:

-17-Atend-of-file or Notthatmanylinesinbuffer Similarly,ifyoutrytomovetoapositionbeforethefirstline,editwillprintoneofthesemessages: Nonzeroaddressrequiredonthiscommand or Negativeaddress−firstbufferlineis1 Thenumberassociatedwithabufferlineistheline’s‘‘address’’,inthatitcanbeusedtolocate theline. Changinglines(c) Youcanalsodeletecertainlinesandinsertnewtextintheirplace.Thiscanbeaccomplishedeasilywiththechange(c)command.Thechangecommandinstructsedittodeletespecifiedlinesandthenswitchtotextinputmodetoacceptthetextthatwillreplacethem.Let’ssay youwanttochangethefirsttwolinesinthebuffer: Thisissomesampletext. Andthisissomemoretext. toread ThistextwascreatedwiththeUNIXtexteditor. Todoso,youtype: :1,2c 2lineschanged ThistextwascreatedwiththeUNIXtexteditor. . : Inthecommand1,2cwespecifythatwewanttochangetherangeoflinesbeginningwith1and endingwith2bygivinglinenumbersaswiththeprintcommand.Theselineswillbedeleted. AfteryoutypeRETURNtoendthechangecommand,editnotifiesyouifmorethanonelinewillbe changedandplacesyouintextinputmode.Anytexttypedonthefollowinglineswillbeinserted intothepositionwherelinesweredeletedbythechangecommand.Youwillremainintext inputmodeuntilyouexitintheusualway,bytypingaperiodaloneonaline.Note thatthenumberoflinesaddedtothebufferneednotbethesameasthenumberoflinesdeleted. ThisistheendofthethirdsessionontexteditingwithUNIX.

-18-Session4 Thislessoncoversseveraltopics,startingwithcommandsthatapplythroughoutthebuffer, characterswithspecialmeanings,andhowtoissueUNIXcommandswhileintheeditor.Thenext topicsdealwithfiles:moreonreadingandwriting,andmethodsofrecoveringfileslostinacrash. Thefinalsectionsuggestssourcesoffurtherinformation. Makingcommandsglobal(g) Onedisadvantagetothecommandswehaveusedforsearchingorsubstitutingisthatifyou haveanumberofinstancesofawordtochangeitappearsthatyouhavetotypethecommand repeatedly,onceforeachtimethechangeneedstobemade.Edit,however,providesawayto makecommandsapplytotheentirecontentsofthebuffer−theglobal(g)command. Toprintalllinescontainingacertainsequenceofcharacters(say,‘‘text’’)thecommandis: :g/text/p The‘‘g’’instructsedittomakeaglobalsearchforalllinesinthebuffercontainingthecharacters ‘‘text’’.The‘‘p’’printsthelinesfound. Toissueaglobalcommand,startbytypinga‘‘g’’andthenasearchpatternidentifyingthe linestobeaffected.Then,onthesameline,typethecommandtobeexecutedfortheidentified lines.Globalsubstitutionsarefrequentlyuseful.Forexample,tochangeallinstancesoftheword ‘‘text’’totheword‘‘material’’thecommandwouldbeacombinationoftheglobalsearchandthe substitutecommand: :g/text/s/text/material/g Notethe‘‘g’’attheendoftheglobalcommand,whichinstructsedittochangeeachandevery instanceof‘‘text’’to‘‘material’’.Ifyoudonottypethe‘‘g’’attheendofthecommandonlythe firstinstanceof‘‘text’’ineachlinewillbechanged(thenormalresultofthesubstitutecommand). The‘‘g’’attheendofthecommandisindependentofthe‘‘g’’atthebeginning.Youmaygivea commandsuchas: :5s/text/material/g tochangeeveryinstanceof‘‘text’’inline5alone.Further,neithercommandwillchange‘‘text’’to ‘‘material’’if‘‘Text’’beginswithacapitalratherthanalower-caset. Editdoesnotautomaticallyprintthelinesmodifiedbyaglobalcommand.Ifyouwantthe linestobeprinted,typea‘‘p’’attheendoftheglobalcommand: :g/text/s/text/material/gp Youshouldbecarefulaboutusingtheglobalcommandincombinationwithanyother−in essence,besureofwhatyouaretellingedittodototheentirebuffer.Forexample, :g//d 72lesslinesinfileafterglobal willdeleteeverylinecontainingablankanywhereinit.Thiscouldadverselyaffectyourdocument,sincemostlineshavespacesbetweenwordsandthuswouldbedeleted.Afterexecutingthe globalcommand,editwillprintawarningifthecommandaddedordeletedmorethanoneline. Fortunately,theundocommandcanreversetheeffectsofaglobalcommand.Youshouldexperimentwiththeglobalcommandonasmallfileoftexttoseewhatitcandoforyou. Moreaboutsearchingandsubstituting Inusingslashestoidentifyacharacterstringthatwewanttosearchfororchange,wehave alwaysspecifiedtheexactcharacters.Thereisalesstediouswaytorepeatthesamestringof characters.Tochange‘‘text’’to‘‘texts’’wemaytypeeither -19- :/text/s/text/texts/ aswehavedoneinthepast,orasomewhatabbreviatedcommand: :/text/s//texts/ Inthisexample,thecharacterstobechangedarenotspecified−therearenocharacters,noteven aspace,betweenthetwoslashmarksthatindicatewhatistobechanged.Thislackofcharacters betweentheslashesistakenbytheeditortomean‘‘usethecharacterswelastsearchedforasthe characterstobechanged.’’ Similarly,thelastcontextsearchmayberepeatedbytypingapairofslasheswithnothing betweenthem: :/does/ Itdoesn’tmeanmuchhere,but :// itdoesillustratetheeditor. (Youshouldnotethatthesearchcommandfoundthecharacters‘‘does’’intheword‘‘doesn’t’’in thefirstsearchrequest.)Becausenocharactersarespecifiedforthesecondsearch,theeditor scansthebufferforthenextoccurrenceofthecharacters‘‘does’’. Editnormallysearchesforwardthroughthebuffer,wrappingaroundfromtheendofthe buffertothebeginning,untilthespecifiedcharacterstringisfound.Ifyouwanttosearchinthe reversedirection,usequestionmarks(?)insteadofslashestosurroundthecharactersyouare searchingfor. Itisalsopossibletorepeatthelastsubstitutionwithouthavingtoretypetheentirecommand.Anampersand(&)usedasacommandrepeatsthemostrecentsubstitutecommand,using thesamesearchandreplacementpatterns.Afteralteringthecurrentlinebytyping :s/text/texts/ youtype :/text/& orsimply ://& tomakethesamechangeonthenextlineinthebuffercontainingthecharacters‘‘text’’. Specialcharacters Twocharactershavespecialmeaningswhenusedinspecifyingsearches:‘‘$’’and‘‘ˆ ’’.‘‘$’’is takenbytheeditortomean‘‘endoftheline’’andisusedtoidentifystringsthatoccurattheend ofaline. :g/text.$/s//material./p tellstheeditortosearchforalllinesendingin‘‘text.’’(andnothingelse,notevenablankspace), tochangeeachfinal‘‘text.’’to‘‘material.’’,andprintthechangedlines. Thesymbol‘‘ˆ ’’indicatesthebeginningofaline.Thus, :s/ˆ /1./ instructstheeditortoinsert‘‘1.’’andaspaceatthebeginningofthecurrentline. Thecharacters‘‘$’’and‘‘ˆ ’’havespecialmeaningsonlyinthecontextofsearching.Atother times,theyareordinarycharacters.Ifyoueverneedtosearchforacharacterthathasaspecial meaning,youmustindicatethatthecharacteristolosetemporarilyitsspecialsignificanceby typinganotherspecialcharacter,thebackslash(\),beforeit.

-20- :s/\\$/dollar/ looksforthecharacter‘‘$’’inthecurrentlineandreplacesitbytheword‘‘dollar’’.Wereitnot forthebackslash,the‘‘$’’wouldhaverepresented‘‘theendoftheline’’inyoursearchratherthan thecharacter‘‘$’’.Thebackslashretainsitsspecialsignificanceunlessitisprecededbyanother backslash. IssuingUNIXcommandsfromtheeditor Aftercreatingseveralfileswiththeeditor,youmaywanttodeletefilesnolongerusefulto youoraskforalistofyourfiles.Removingandlistingfilesarenotfunctionsoftheeditor,andso theyrequiretheuseofUNIXsystemcommands(alsoreferredtoas‘‘shell’’commands,as‘‘shell’’is thenameoftheprogramthatprocessesUNIXcommands).Youdonotneedtoquittheeditorto executeaUNIXcommandaslongasyouindicatethatitistobesenttotheshellforexecution. TousetheUNIXcommandrmtoremovethefilenamed‘‘junk’’type: :!rmjunk ! : Theexclamationmark(!)indicatesthattherestofthelineistobeprocessedasashellcommand.Ifthebuffercontentshavenotbeenwrittensincethelastchange,awarningwillbe printedbeforethecommandisexecuted: [Nowritesincelastchange] Theeditorprintsa‘‘!’’whenthecommandiscompleted.Thetutorial‘‘Communicatingwith UNIX’’describesusefulfeaturesofthesystem,ofwhichtheeditorisonlyonepart. Filenamesandfilemanipulation Throughouteacheditingsession,editkeepstrackofthenameofthefilebeingeditedasthe currentfilename.Editremembersasthecurrentfilenamethenamegivenwhenyouenteredthe editor.Thecurrentfilenamechangeswhenevertheedit(e)commandisusedtospecifyanewfile. Onceedithasrecordedacurrentfilename,itinsertsthatnameintoanycommandwhereafilenamehasbeenomitted.Ifawritecommanddoesnotspecifyafile,edit,aswehaveseen,supplies thecurrentfilename.Ifyouareeditingafilenamed‘‘draft3’’having283linesinit,youcanhave theeditorwriteontoadifferentfilebyincludingitsnameinthewritecommand: :wchapter3 "chapter3"[newfile]283lines,8698characters Thecurrentfilenamerememberedbytheeditorwillnotbechangedasaresultofthewritecommand.Thus,ifthenextwritecommanddoesnotspecifyaname,editwillwriteontothecurrent file(‘‘draft3’’)andnotontothefile‘‘chapter3’’. Thefile(f)command Toaskforthecurrentfilename,typefile(orf).Inresponse,theeditorprovidescurrent informationaboutthebuffer,includingthefilename,yourcurrentposition,thenumberoflinesin thebuffer,andthepercentofthedistancethroughthefileyourcurrentlocationis. :f "text"[Modified]line3of4--75%-- Ifthecontentsofthebufferhavechangedsincethelasttimethefilewaswritten,theeditorwill tellyouthatthefilehasbeen‘‘[Modified]’’.Afteryousavethechangesbywritingontoadiskfile, thebufferwillnolongerbeconsideredmodified:

-21- :w "text"4lines,88characters :f "text"line3of4--75%-- Readingadditionalfiles(r) Theread(r)commandallowsyoutoaddthecontentsofafiletothebufferataspecified location,essentiallycopyingnewlinesbetweentwoexistinglines.Touseit,specifythelineafter whichthenewtextwillbeplaced,theread(r)command,andthenthenameofthefile.Ifyou haveafilenamed‘‘example’’,thecommand :$rexample "example"18lines,473characters readsthefile‘‘example’’andaddsittothebufferafterthelastline.Thecurrentfilenameisnot changedbythereadcommand. Writingpartsofthebuffer Thewrite(w)commandcanwriteallorpartofthebuffertoafileyouspecify.Weare alreadyfamiliarwithwritingtheentirecontentsofthebuffertoadiskfile.Towriteonlypartof thebufferontoafile,indicatethebeginningandendinglinesbeforethewritecommand,for example :45,$wending Herealllinesfrom45throughtheendofthebufferarewrittenontothefilenamedending.The linesremaininthebufferaspartofthedocumentyouareediting,andyoumaycontinuetoedit theentirebuffer.Youroriginalfileisunaffectedbyyourcommandtowritepartofthebufferto anotherfile.Editstillrememberswhetheryouhavesavedchangestothebufferinyouroriginal fileornot. Recoveringfiles Althoughitdoesnothappenveryoften,therearetimesUNIXstopsworkingbecauseofsome malfunction.Thissituationisknownasacrash.Undermostcircumstances,edit’scrashrecovery featureisabletosaveworktowithinafewlinesofchangesbeforeacrash(oranaccidentalphone hangup).Ifyoulosethecontentsofaneditingbufferinasystemcrash,youwillnormallyreceive mailwhenyouloginthatgivesthenameoftherecoveredfile.Torecoverthefile,entertheeditor andtypethecommandrecover(rec),followedbythenameofthelostfile.Forexample,to recoverthebufferforaneditsessioninvolvingthefile‘‘chap6’’,thecommandis: :recoverchap6 Recoverissometimesunabletosavetheentirebuffersuccessfully,soalwayscheckthecontentsof thesavedbuffercarefullybeforewritingitbackontotheoriginalfile.Forbestresults,writethe buffertoanewfiletemporarilysoyoucanexamineitwithoutrisktotheoriginalfile.Unfortunately,youcannotusetherecovercommandtoretrieveafileyouremovedusingtheshellcommandrm. Otherrecoverytechniques Ifsomethinggoeswrongwhenyouareusingtheeditor,itmaybepossibletosaveyourwork byusingthecommandpreserve(pre),whichsavesthebufferasifthesystemhadcrashed.If youarewritingafileandyougetthemessage‘‘Quotaexceeded’’,youhavetriedtousemoredisk storagethanisallottedtoyouraccount.Proceedwithcautionbecauseitislikelythatonlyapart oftheeditor’sbufferisnowpresentinthefileyoutriedtowrite.Inthiscaseyoushouldusethe shellescapefromtheeditor(!)toremovesomefilesyoudon’tneedandtrytowritethefile again.Ifthisisnotpossibleandyoucannotfindsomeonetohelpyou,enterthecommand -22- :preserve andwaitforthereply, Filepreserved. Ifyoudonotreceivethisreply,seekhelpimmediately.Donotsimplyleavetheeditor.Ifyoudo, thebufferwillbelost,andyoumaynotbeabletosaveyourfile.Ifthereplyis‘‘Filepreserved.’’ youcanleavetheeditor(orlogout)toremedythesituation.Afterapreserve,youcanusethe recovercommandoncetheproblemhasbeencorrected,orthe−roptionoftheeditcommandif youleavetheeditorandwanttoreturn. Ifyoumakeanundesirablechangetothebufferandtypeawritecommandbeforediscoveringyourmistake,themodifiedversionwillreplaceanypreviousversionofthefile.Shouldyou everloseagoodversionofadocumentinthisway,donotpanicandleavetheeditor.Aslongas youstayintheeditor,thecontentsofthebufferremainaccessible.Dependingonthenatureof theproblem,itmaybepossibletorestorethebuffertoamorecompletestatewiththeundocommand.Afterfixingthedamagedbuffer,youcanagainwritethefiletodisk. Furtherreadingandotherinformation Editisaneditordesignedforbeginningandcasualusers.Itisactuallyaversionofamore powerfuleditorcalledex.Theselessonsareintendedtointroduceyoutotheeditoranditsmore commonly-usedcommands.Wehavenotcoveredalloftheeditor’scommands,butaselectionof commandsthatshouldbesufficienttoaccomplishmostofyoureditingtasks.Youcanfindout moreabouttheeditorintheExReferenceManual,whichisapplicabletobothexandedit.The manualisavailablefromtheComputingServicesLibrary,218EvansHall.Onewaytobecome familiarwiththemanualistobeginbyreadingthedescriptionofcommandsthatyoualready know. Usingeexx Asyoubecomemoreexperiencedwithusingtheeditor,youmaystillfindthateditcontinuestomeetyourneeds.However,shouldyoubecomeinterestedinusingex,itiseasytoswitch. Tobeginaneditingsessionwithex,usethenameexinyourcommandinsteadofedit. Editcommandsworkthesamewayinex,buttheeditingenvironmentissomewhatdifferent. Youshouldbeawareofafewdifferencesthatexistbetweenthetwoversionsoftheeditor.In edit,onlythecharacters‘‘ˆ ’’,‘‘$’’,and‘‘\’’havespecialmeaningsinsearchingthebufferorindicatingcharacterstobechangedbyasubstitutecommand.Severaladditionalcharactershavespecialmeaningsinex,asdescribedintheExReferenceManual.Anotherfeatureoftheeditenvironmentpreventsusersfromaccidentlyenteringtwoalternativemodesofediting,openandvisual, inwhichtheeditorbehavesquitedifferentlyfromnormalcommandmode.Ifyouareusingexand theeditorbehavesstrangely,youmayhaveaccidentlyenteredopenmodebytyping‘‘o’’.Type theESCkeyandthena‘‘Q’’togetoutofopenorvisualmodeandbackintotheregulareditor commandmode.ThedocumentAnIntroductiontoDisplayEditingwithViprovidesafulldiscussionofvisualmode.

-23-Index addressing,seelinenumbers ampersand,20 appendmode,6-7 append(a)command,6,7,9 ‘‘Atendoffile’’(message),18 backslash(\),21 buffer,3 caret(ˆ ),10,20 change(c)command,18 commandmode,5-6 ‘‘Commandnotfound’’(message),6 contextsearch,10-12,19-21 controlcharacters(‘‘ˆ ’’notation),10 control-H,7 copy(co)command,15 corrections,7,16 currentfilename,21 currentline(.),11,17 delete(d)command,15-16 dial-up,5 disk,3 documentation,3,23 dollar($),10,11,17,20-21 dot(.)11,17 edit(texteditor),3,5,23 edit(e)command,5,9,14 editingcommands: append(a),6,7,9 change(c),18 copy(co),15 delete(d),15-16 edit(texteditor),3,5,23 edit(e),5,9,14 file(f),21-22 global(g),19 move(m),14-15 number(nu),11 preserve(pre),22-23 print(p),10 quit(q),8,13 read(r),22 recover(rec),22,23 substitute(s),11-12,19,20 undo(u),16-17,23 write(w),8,13,21,22 z,12-13 !(shellescape),21 $=,17 +,17 −,17 //,12,20 ??,20 .,11,17 .=,11,17 enteringtext,3,6-7 erasing characters(ˆ H),7 lines(@),7 errorcorrections,7,16 ex(texteditor),23 ExReferenceManual,23 exclamation(!),21 file,3 file(f)command,21-22 filerecovery,22-23 filename,3,21 global(g)command,19 inputmode,6-7 Interrupt(message),9 linenumbers,seealsocurrentline dollarsign($),10,11,17 dot(.),11,17 relative(+and−),17 list,10 loggingin,4-6 loggingout,8 ‘‘Loginincorrect’’(message),5 minus(−),17 move(m)command,14-15 ‘‘Negativeaddress—firstbufferlineis1’’(message),18 ‘‘Nocurrentfilename’’(message),8 ‘‘Nosuchfileordirectory’’(message),5,6 ‘‘Nowritesincelastchange’’(message),21 non-printingcharacters,10 ‘‘Nonzeroaddressrequired’’(message),18 ‘‘Notaneditorcommand’’(message),6 ‘‘Notthatmanylinesinbuffer’’(message),18 number(nu)command,11 password,5 period(.),11,17 plus(+),17 preserve(pre)command,22-23 print(p)command,10 program,3 prompts %(UNIX),5 :(edit),5,6,7 (append),7 question(?),20 quit(q)command,8,13 read(r)command,22 recover(rec)command,22,23 -24-recovery,seefilerecovery references,3,23 remove(rm)command,21,22 reversecommandeffects(undo),16-17,23 searching,10-12,19-21 shell,21 shellescape(!),21 slash(/),11-12,20 specialcharacters(ˆ ,$,\),10,11,17,20-21 substitute(s)command,11-12,19,20 terminals,4-5 textinputmode,7 undo(u)command,16-17,23 UNIX,3 write(w)command,8,13,21,22 zcommand,12-13