Top Banner

of 24

Grep and UNIX

Jun 02, 2018

Download

Documents

CKEITH14
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/10/2019 Grep and UNIX

    1/24

    chapter

    4

    39

    In this chapter we discuss the following commands:

    UnixCommand DOSCommand Description

    cd CD change to another directory

    clear CLS clear the screen

    cp COPY copya file

    grep FIND search for a pattern in a filelpr PRINT print a file

    ls DIR list the files in a directory

    mkdir MKDIR create a directory

    more MORE displaya file one screenful at

    a time

    mv RENAME rename a file

    pwd CHDIR print the name of the current

    working directory

    rm DEL delete a file

    rmdir RMDIR delete a directory

    4.1 Introduction

    There are a number of fundamental commands in Unix that everyuser needs

    to learn right away. In Chapter 2 we covered the most important commands

    relating to accounts: login, logout,and passwd; in Chapter 3we covered the

    most important commands relating to theU

    nixReference Manual: ap

    r

    opos,

    man,and whatis.

    In this chapter we cover a number of veryimportant commands relating to

    files and directories.These commands handle manyof the routine functions that

    a typical user performs on a dailybasis.We describe the most common features of

    TOP TEN

    MOST USEFUL

    UNIX COMMANDS

  • 8/10/2019 Grep and UNIX

    2/24

    Chapter 4Top Ten Most Useful Unix Commands

    40

    each of these commands here. Later in the book, we will delve into more specia

    ized uses of the commands. Having mastered these ten1commands, you will b

    able to work on a Unix system and perform essential functions such as

    * list the files in a directory.

    * display command output one screenful at a time.

    * change to another directory.* search for a pattern in a file.

    * print a file.

    * create a directory to store files in.

    * copy a file.

    * rename a file.

    * delete a file.

    * delete a directory.

    * clear the screen.

    We cover the top tencommands in the order you will probably encount

    them.

    4.2 ListingYour Filesls

    Command

    The ls command name is an abbreviation for list. It is used to list you

    directories and files. Suppose that you have just logged onto a Unix system. Yo

    are now in a position to do some useful work. Initially, you will encounter th

    Unix prompt

    %

    When you log into your account, the system by default places you in an areknown as your home directory. This initial file space contains some very importan

    files and is your home base from which you will begin working. (On some opera

    ing systems, directories are called folders.)

    In the Unix operating system, directories and files are organized into a tre

    like hierarchy. Figure 4.1 depicts such a sample structure graphically. It is wort

    going over some basic definitions about trees since the terminology associate

    with them has been adopted by Unix, and we make use of it throughout th

    book.

    1. All right, twelve.

    In Figure 4.1 the circles represent nodesand the lines between the nodes rep

    resent edges. The tree is oriented so the part highest up on the page is referred t

    as the top;the other end of the tree is referred to as the bottom. The node at th

    top of the tree, in this case A, is called the root. If there is an edge between tw

  • 8/10/2019 Grep and UNIX

    3/24

    41

    4.2Listing Your Filesls Command

    A

    B C

    HGFED

    JI

    Figure 4.1ATree

    nodes, we say the nodes are adjacent.For example, nodes Cand Fare adjacent

    whereas nodes Fand Gare not.The childrenofa node are the nodes adjacent to

    it and also below it in the picture.For example, Dand Eare the two children of

    B.Aparentofa node is the node that is above it and adjacent to it.For example,

    bin dev

    . . . . . .

    . . .. . .. . .

    . . .

    . . . . . .

    . . .

    etc usr

    tmplocalgameswhoisalias

    manhome

    shelly tarvaresgroves

    Figure 4.2ASimplified Representation ofthe UnixFile System

  • 8/10/2019 Grep and UNIX

    4/24

    Chapter 4Top Ten Most Useful Unix Commands

    42

    C is the parent of F, G, and H. A pathis a sequence of adjacent nodes in the tre

    For example, A-C-F is a path, whereas D-A-C-H is not. We are usuallyintereste

    in paths that go down the tree.

    In Figure 4.2we depict a sample Unixfile space in the formof a tree. We d

    not include circles for nodes in the tree, but insteadjustwrite in a directoryor fi

    name to represent a node. In the figure onlyalias

    andwhois

    represent files;thother nodes represent directories. The directoryat the top of the tree is known

    the rootdirectoryand is represented bythe /(forward slash)character.

    Suppose A and Bare directories in a file space represented bya tree T. We s

    Bis a subdirectoryof A, if there is a path fromA to Bgoingdown T. So, if allth

    nodes in Figure 4.1represent directories, then Band C would be subdirectori

    of A. In addition, F, G, and H are subdirectories of C.

    2. The word underis used because of the physicalrelationship shown in Figure 4.2.

    Some standard subdirectories under2 the root directory on a large Un

    systemare bin, dev, etc, and usr. Unixusers relyon the words upand down

    to indicate relative positions in a directoryhierarchy. For example, shellyis dow

    one fromhomeand home is up one fromshelly. That is, home is the parendirectoryof shelly. Youwillhear expressions such as move down two directo

    riesor go to the parent directory.

    When youinitiallylogin to your account, bydefault youare placed in you

    home directory.

    Startingfromthe root directoryand proceedingthrough the tree untilyo

    reach your home directoryresults in a path to your home directory. For exampl

    usr-local-home-groves is a path to Brian Groves home directory. When th

    directorynames youpass through are concatenated together, the result is a pat

    name. The pathname for Brians home directoryis

    /usr/local/home/groves

    Pathnames can be full or relative. A full pathname specifies a complete pat

    through the directorystructure startingat the root directory, whereas a relativ

    pathname specifies a path relative to some startingposition. For example,we hav

    /bin/whoisas a fullpathname and local/home/tarvaresas a relative pathnam

    We willexplore the Unixfile and directorystructure further in Chapters 1011

    The first forward slash in a pathname represents the root directory. Addition

    forward slashes in a pathname separate the names of subdirectories. Figure 4

    shows John Tarvaresdirectorystructure. We willuse his account as a modelt

    describe concepts throughout this chapter.

  • 8/10/2019 Grep and UNIX

    5/24

    43

    4.2Listing Your Filesls Command

    ABBOTT, classes, HTML, andmiscarechild subdirectoriesof tarvares.

    ThefilebudiscontainedinthedirectoryABBOTT.Therearethreefilesinthe

    directoryHTML.

    tarvares

    HTML miscclassesABBOTT

    index.html work.htmla.jpgbud

    Figure 4.3John TarvaresDirectoryand File Structure

    IfJohnentersthecommandline

    %ls

    thedirectoriesinhishomedirectorywillbelistedasshownbelow.

    ABBOTT classes

    HTML misc

    Thelscommandlistsfilesanddirectoriescontained inthedirectorywhere

    thelscommandisexecutedfrom.Whenyoufirstlogin, thiswillbefromyour

    homedirectory.Laterinthischapterwedescribehowtochangedirectories.If

    youchange toanotherdirectory, sayadirectorycalledHTML, andenter the

    lscommand, thefilesinthedirectoryHTMLwillbelisted.InJohnscasethis

    resultsinalistingofthefilesa.jpg, index.html, andwork.html.

    The current working directory, sometimes called the working directory for

    short, refers to thedirectoryyouare in.Unixprovides thepwdcommand to

    displaythefullpathnameofthecurrentworkingdirectory, allowingyoutofind

    outwhichdirectoryyouarein.Aftermovingupanddownthedirectorytreea

    largenumberoftimes, itiseasytolosetrackofwhereyouare.

    IfJohnentersthecommand

    %pwd

    fromhishomedirectorytheresultis

    /usr/local/home/tarvares

  • 8/10/2019 Grep and UNIX

    6/24

    Chapter 4Top Ten Most Useful Unix Commands

    44

    assuming he is the same Tarvares as shown in Figure 4.2.

    Next we describe two important flags to the lscommand. As you have see

    from the examples oflspresented above,byexecuting the lscommand we lear

    onlyabout what files and directories are in the current working directory. We d

    not actuallyget anydetails about the files themselves,such as when theywere cr

    ated or how manybytes theyare. To obtain detailed information about thefile

    the lflag maybe used. The l(the letter l,not the number 1)stands for long

    form. Asample output for the command

    %ls -l

    is shown in Figure 4.4. Notice that a lot ofinformation about a file is displaye

    We explain allthis information in detailin Chapter 11. For now,remember th

    column 1pertains to file permissions,column 5to file size in number ofbyte

    and columns 68to the last modification date ofthe file.

    total 7060

    drwx------ 2 tweed faculty 512 Aug 18 1998 SONGS

    -rw------- 1 tweed faculty 5204 Apr 28 1995 atrail.tex

    -rw------- 1 tweed faculty 4048 Jun 28 1996 comrades

    -rw------- 1 tweed faculty 1638 Aug 5 1994 ep15.tex

    -rw------- 1 tweed faculty 3292 Jul 19 1994 highs.tex

    -rw------- 1 tweed faculty 2557 Oct 29 13:43 iron.txt

    -rw------- 1 tweed faculty 299 Oct 1 13:08 labels.tex

    -rw------- 1 tweed faculty 312 Oct 1 13:10 labels2.tex

    -rw------- 1 tweed faculty 518 Feb 1 16:32 loop.aasu

    -rw------- 1 tweed faculty 3579380 Feb 24 18:46 bullalgs

    drwx------ 2 tweed faculty 1024 Dec 6 21:11 recs

    -rw------- 1 tweed faculty 1869 Jun 8 1998 rent.sav

    Figure 4.4Sample Output from an ls lCommand

    To list allofthe files and directories contained in a directory,you use the

    flag to the lscommand. That is,

    %ls -a

    lists allfiles in the current working directory. Unix directories contain speci

    hidden files. Byusing theaflag to the lscommand,you are able to view the

    files as well. We cover hidden files in Section 10.3. Asample output ofthe ls

    command is shown in Figure 4.5. Notice severalhidden files are displayed,amon

    others,.,..,.cshrc,.login,and .netscape. Everydirectoryalways contains the

    and ..hidden files. These refer to the current working directory(the directo

    itself)and the directorys parent directory.

  • 8/10/2019 Grep and UNIX

    7/24

    45

    4.2Listing Your Filesls Command

    . africa

    .. albany

    .addressbook february

    .cshrc fi sh

    .history fritos

    .hotjava moneymatters

    .login monkey

    .logout zebra

    .netscape

    Figure 4.5Sample Output from an ls aCommand

    You may combine the different options to Unix commands. For example, the

    command

    %ls -la

    lists all material contained in the current workingdirectory in the longform. This

    produces the same result as entering

    %ls -al

    The order of the specified options does not matter;they are both applied.

    We will describe one final use of the lscommand. There are times when you

    want to copy a file from another directory to the current workingdirectory. You

    may remember the pathname of the directory the file is stored in, but you may

    not remember the name of the file itself. You can list the contents of this other

    directory by specifyingits name as an argument to thels

    command.For example, suppose you are in the directory called

    /export/local/home/riddle

    and that you would like to copy a file from the directory

    /export/local/home/messner/climbs/public

    to your directory but cannot remember the name of the file. The command

    %ls /export/local/home/messner/climbs/public

    executed from your directory will provide you with a list of files in the other

    directory. Once you locate the name of the file, you can proceed to copy it usingthe technique described in Section 4.8.

    You should execute the command line

    %manls

    to learn more about the lscommand.

  • 8/10/2019 Grep and UNIX

    8/24

    Chapter 4Top Ten Most Useful Unix Commands

    46

    Exercises

    1. Execute the lscommandfromyourhome directory. Howmanyfile

    doyou have?Howmanydirectories?Nowexecute the commandls

    a. Howmanyitemsare listed?Howmanyhiddenfilesare there?

    2. Howmanyoptionstothe lscommandare there onyoursystem?

    Describe twointerestingoptionsdifferent fromthose coveredinth

    section.

    3. What isthe fullpathname foryourhome directory?

    4.3 Displayinga Filemore Command

    InChapter2you first encountered the more command. The more comman

    providesaconvenient waytoviewthe contentsofafile one screenfulat atim

    Forexample,enteringthe command

    %more index.html

    displaysone screenfulof content of the file index.html. Hitting the Spaceb

    bringsupthe next screenfuloftext,andtypingqquitsthe morecommandan

    bringsyou backtothe Unix prompt. The morecommandonlyallowsyou tovie

    the file. Toalterthe filescontentsyou needtouse atext editor.

    Tryenteringthe command

    %man man

    onyour system. The Unix Reference Manual documentation about the ma

    commandconsistsofmore thanone screenfulofinformation. Inthe lowerleft

    the screen,the morecommandtellsyou what percentage ofthe file hasalreabeendisplayed. Thus,adisplaysuch as

    ---More---(13%)

    indicatesyou have seen13%ofthe file,sothere isanother87%ofthe file that h

    yet tobe displayed. The percentagesare veryhelpfulandlet you make ament

    note ofwhere you are inthe file. Forexample,you mayrecallthat you hadsee

    some important informationthat was47%ofthe waythrough afile andthenb

    able toeasilyreturntothe information. Onmost Unix systems,you canpress

    while viewingafile with moreandyou willbe returnedtothe precedingscree

    ofinformationorremainat the first screenifyou have not movedforwardinthfile.

    The morecommandalsoprovidesyou with amechanism forsearching fo

    auser-specifiedpatternofcharactersinafile. Toexecute asearch inafile bein

    displayedbymore,you simplytype /andthenthe patternyou are lookingfo

    Suppose you were lookingforthe patternsailboat. You wouldtype

  • 8/10/2019 Grep and UNIX

    9/24

    47

    4.4Changing Directorycd Command

    /sailboat

    The moreprogramwouldthensearch forwardfromwhere youcurrentlyare in

    the file andhighlightthe firstoccurrence ofthe wordsailboat it found.Ifthe

    patternwere notpresentinthe file,morewouldindicate thatthe patternwasnot

    found.Tolocate subsequentoccurrencesofapatternyoujustentered,youneed

    onlytype / andpressEnter.Anotherconvenientfeature ofmoreisthe soption.Thisoptiontellsmore

    tosqueeze consecutive blanklinesintoasingle blankline.Inthiswayadditional

    informationcanbe displayedonthe screen.So,forexample,todisplaythe file

    data.txtwith extrablanklinessqueezedoutofit,youwouldenterthe command

    %more -sdata.txt

    The morecommandhasanumberofotherinterestingfeatures.Youshould

    execute the commandline

    %manmore

    tolearnadditionalinformationaboutit.

    TwootherUnixprograms fordisplayingfilesare less andpg.Some users

    preferlessovermorebecause lessallowsyoutoscrollboth downandup.The

    commandname lesswaschosensarcastically;infact,lessprovidesgreaterfunc-

    tionalitythanmore.Youcandoamanonlessandpgtofindouthowtouse

    themandhowtheydifferfrommore.

    Exercises

    1. Canthe morecommandtake severalarguments?Ifso,whatisthe

    result?

    2. Performamanmorecommand.Howmanytimesdoesthe pattern

    manualoccurinthe manpageformore?Howmanytimesdoes

    the patternManualoccur? Isthe searchingdone withinthe more

    commandcase sensitive?

    3. Are the commandslessandpgavailable onyoursystem?Compare

    andcontrastthemwith the morecommand.

    4.4 Changing Directorycd Command

    The Unix file system is arranged into a hierarchy of directories conveniently

    represented by a tree.Asyou organize yourwork,youwill need to be able

    to navigate through the tree. Tomove to another directory,you use the cd

    command, short for change directory. The cd command by itselfwith no

    argumentswillplace youinyourhome directoryregardlessofwhich directory

    yourcurrentworkingdirectoryis.

  • 8/10/2019 Grep and UNIX

    10/24

    Chapter 4Top Ten Most Useful Unix Commands

    48

    To verify a change of directory, you can use the pwdcommand.The outpu

    of the pwdcommand is the fullpathname of the directory you are in.Suppo

    Jenny Shelly just logged into her account with userid shelly.Figure 4.2illustrat

    the location of Jennys file space graphically.If Jenny executed the command

    %pwd

    for output she would see

    /usr/local/home/shelly

    By specifying a pathname as the argument to the cd command, you ca

    change to other directories. For example, consider John Tarvares file spa

    depicted in Figure 4.6.To transfer into his Web directory (HTML), John ca

    enter

    %cd/usr/local/home/tarvares/HTML

    fromany other directory in the Unixfile system.Notice that John has specifie

    a full pathname. Typing in a full pathname every time you want to changdirectories is time consuming;it is often more efficient to use a relative pathnam

    For example, fromhis home directory, tavares, John could have typed

    %cdHTML

    to achieve the same result.That is, relative to his home directory, the directo

    HTML is one leveldown.The cdcommand followed by an explicit directo

    name will take you to that directory if it is a child subdirectory of th

    current working directory.In other words, to move to a child directory calle

    childsubdirectoryfromwithin its parent directory, you simply enter

    %cdchildsubdirectory

    tarvares

    HTML miscclassesABBOTT

    index.html work.htmla.jpgbud

    Figure 4.6John TarvaresFile Space

  • 8/10/2019 Grep and UNIX

    11/24

    49

    4.4Changing Directorycd Command

    To move up one level in a directory hierarchy, follow the cdcommand with

    two dots

    %cd ..

    The two dotsrepresent the parent directoryof where you are currently located.

    Using relative path nameswhen navigating through the file structure can save

    a lot of typing time. To move from within hisHTML directory to hismisc

    directory, John can enter

    %cd ../misc

    Recall that Unix iscase sensitive.Thus, it isimportant to type directory names

    exactly asthey appear.

    The tilde (~)symbol isused to refer to your home directory.For example,

    ~tarvares

    isexpanded automatically to

    /usr/local/home/tarvares

    The tilde character can prove very useful for movingaround a directory structure.

    Asan example, suppose your current workingdirectory is

    /usr/local/home/tarvares/brown/bags/computers

    and you would like your current workingdirectory to be

    /usr/local/home/tarvares/pool/tables/balls

    The command

    %cd ~/pool/tables/balls

    can be used to accomplish this change of directories.Contrast thiswith other

    methodsfor movinginto thisdirectory, which require considerably more typing.

    You should execute the command line

    %mancd

    to learn more about the cdcommand.

    Exercises

    1. Consider the directory and file structure shown in Figure 4.7.Sup-

    pose you were initially located in the fooddirectory.Provide the cdcommandsthat require the least number of charactersto be typed to

    perform the followingtasks:

    a. move to the omelettedirectory

    b. from the omelettedirectory move to the cerealdirectory

  • 8/10/2019 Grep and UNIX

    12/24

    Chapter 4Top Ten Most Useful Unix Commands

    50

    restaurants

    /

    food

    McDonalds PinkHousecapecereal omelette spaghetti

    Figure 4.7Directoryand File Structure Used in the Exercises

    c. from the cerealdirectorymove to the capedirectory

    d. from the capedirectorymove to the omelettedirectory

    e. returnto the home directory

    2. What isthe effect of the commandcd .?

    3. What are the childsubdirectoriesof the root directoryonyour

    system?

    4. Are there anyinterestingflagsto the cdcommand?If so,describe

    two of them.

    4.5 Searchingfor a Patterngrep Command

    There willbe manytimeswhenyouwant to search afile for apattern. It wouldb

    convenient if youcoulddo thiswithout usingatext editor. If youcouldperfor

    such asearch from the operatingsystem,youwouldnot have to go through th

    usualstepsof openingthe file with atext editor,usingthe editorssearch facilit

    and thenclosingthe file. Unixprovidesthe grepcommand for searchingafi

    for apattern. In fact,grepallowsyou to search an entire directory of files o

    evenanentire file system for apattern. The grepcommandisapowerfulsearc

    mechanism that providesaconvenient notation,allowingyouto specifycomple

    patternsto search for.

    The wordgrepisanacronym for globalregular expressionprint. Regula

    expressionsare animportant concept incomputer science. Youcanthinkof the

    as a means to compactly express patterns. We consider a couple of examplinvolvingthe use of the grepcommand.

    Suppose youare residinginadirectorythat yieldsthe followingdisplaywhe

    youexecute anlscommand:

    annotation.tex california.tex game.c words.favorites

    buffalo.txt denver.txt golfi ng.txt

  • 8/10/2019 Grep and UNIX

    13/24

    51

    To search the file words.favoritesfor the wordzooks,youenter the com-

    mand

    %grep zooks words.favorites

    The output ofthis commandis a displayofall lines inthe file words.favoritesthat

    containthe wordzooks.Inthis case,the wordappearedtwice andthe following

    was displayedas output:

    yikesanexclamation,also see zooks.

    zooksanexclamation,also see yikes.

    Ifthe wordwere not present in the file,youwouldhave beenreturned to the

    Unixprompt without seeinganyoutput.

    This example illustrates that the first argument to the grepcommandis the

    patternyouare lookingfor,andthe secondargument specifies the file(s)to search

    for the patternin.The patterncanbe specifiedusinga regular expression.We will

    lookat various examples ofspecifyingpatterns below,andwe will also consider

    several ways ofspecifyingfiles to search in.

    To search for the wordzooksinthe files games.candwords.favoritessimul-

    taneously,youcouldenter the followingcommand:

    %grep zooks games.cwords.favorites

    The output inthis case is the same as before,since inour case the wordzooks

    does not appear inthe file games.c.

    The grep command has been optimized and it searches veryquickly even

    whenyouask it to look inmany large files at once.Suppose youhadusedthe

    wordelephantinone ofthe files inthe directoryunder considerationbut could

    not remember which file.Youcanuse the grepcommandas follows to locate the

    desiredfile:

    %grep elephant *

    The asterisk(*)serves as a wildcard.Inthis context it tells the grepcommand

    to search all files inthe directoryfor the patternelephant.That is,*means match

    all file names.The grepcommandwill search all the files inthe directoryfor the

    wordelephant.The output ofthe commandis the name ofeach file where the

    patternwas foundfollowedbythe lines inthe file where the patternoccurred.

    Thefile extensionis the part ofa file name occurringafter the last period.For

    example,the file extensionofmain.tex is tex.Ifa file has anextensionofabc,

    we refer to it as anabcfile.For example,main.texis calleda tex(pronounced

    tech)file.

    Suppose youwantedto search onlyfiles with anextensionoftexfor the pat-

    ternPetertheGreat.This couldbe accomplishedbythe followingcommand:

    4.5Searching for a Patterngrep Command

  • 8/10/2019 Grep and UNIX

    14/24

    Chapter 4Top Ten Most Useful Unix Commands

    52

    %grep Peter the Great *.tex

    There are two things to notice about this command. Since the pattern we a

    looking for contains blank spaces, we put the pattern in single quotes. Otherwis

    grepwould interpret part of the pattern as a file name to search. This would resu

    in an error message since there is no file in our directorycalled the.

    The second thing to notice is how we were able to specifyall files ending witthe texextension using *.tex. The star means match anypatternand the .te

    means the file name must end with these four characters:., t, e, and xin order.

    If you executed the command ls *.texon this directory, you would see th

    following output:

    annotation.txt california.tex

    Thus, the grepcommand

    %grep Peter the Great *.tex

    searches bothannotation.t

    ex

    andcalifo

    rnia.t

    ex

    for the patternPeter

    th

    Great.

    The grepcommand provides notation for efficientlyspecifying patterns. W

    have alreadyseen that the *means match anypattern.The .is used to matc

    anysingle character. The Unixregular expression

    a.b.c

    means match anypattern that consists of five characters, where the first charact

    is an a, the third character is a b, the fifth character is a c, and characters tw

    and four can be anysingle symbols. For example, the pattern atbvcmeets the

    criteria as does the patterna$bZ

    c.

    If you type in a character that has a special meaning to grep, for example,

    or ., you should escapethe character with the \symbol. This tells grepthat yo

    want the character to be interpreted literallyso that its special meaning is disr

    garded. For example, suppose you wanted to look for the pattern a.b.c. That i

    you wanted to find the five characters a, ., b, ., and cin this order. The followin

    command would search all files with a txtextension for this pattern:

    %grep a\.b\.c*.txt

    Notice that we have escaped the two dots so that theyare matched exactlyrath

    than telling the grepcommand to match anytwo characters.The command line

    %grep [A-Z]\. *.tex

    finds all lines in all files with the extension texthat contain a capital letter followe

    by a period. You can specifya range of characters to grep bydisplaying the

  • 8/10/2019 Grep and UNIX

    15/24

    53

    in square brackets with a dash in between. A range of lowercase letters may be

    specified similarly. For example, [dg]is used to match one of the characters d,

    e, f, and g.

    There are many other useful ways of specifying patterns to grep. You should

    execute the command line

    %man grep

    to learn more about the grepcommand.

    Exercises

    1. Write grepexpressions to search the file named computersfor the

    following patterns:

    a. the word personal

    b. the phrase personalcomputer

    c. the phrase PersonalComputer

    2. On many Unix systems there is a file called /usr/words/dict. Thisfile contains a long list of words used by spell-checking programs.

    Write a grepexpression to search this file for any words that contain

    all the vowels in consecutive order. That is, you are looking for words

    that contain the letters a, e, i, o, and uin this order. There can

    be other letters interspersed between the vowels. What words did

    you find?

    3. You will need to read the manpagefor grepto complete this

    exercise. Write grepexpressions to search all files in a directory for

    the following patterns:a. any line that begins with a capital letter

    b. any line that ends with a capital letter

    c. a pattern consisting of three vowels in a row

    d. the pattern a(b)..&*, where the quotes arepart of the pattern

    you want to find

    4.6 Printinglpr Command

    It is very important to be able to print files from a computer system. Unix

    provides the command lpr for this purpose. The command name lpr is anabbreviation for line printer.On many systems a default printer will be set up

    for you to use. That is, if you send a file to the printer, the default printer will be

    the physical printer that actually outputs your file. If a default printer has been set

    up, you can print the file bannerfrom your current working directory using the

    command line

    4.6Printinglpr Command

  • 8/10/2019 Grep and UNIX

    16/24

    Chapter 4Top Ten Most Useful Unix Commands

    54

    %lpr banner

    Suppose you want to print the same file to a printer named laserrather tha

    to the default printer.You would enter the followingcommand line:

    %lpr -Plaser banner

    On some systems you would enter

    %lp -Dlaser banner

    or

    %lp -dlaser banner

    The dand Dflags stand for destination.The argument followingthese fla

    tells the system the name ofthe printer on which to print your file.You will nee

    to checkto see ifyour system uses lpror lp,or some other print command.

    It is important to send the correct file types to the printer.Ifyou send th

    wrongtype offile,the output may be nonsense;you could waste a lot ofpaper;

    you could jam the printer.Today many printers handle plain textand PostScrifiles.You should try to learn what formats your local printer can handle.

    Many printers do not handle dvi files properly.The LATEX documentatio

    preparation system that we cover in AppendixHgenerates dvifiles as output.

    is not a good idea to send a dvifile directly to a printer.In AppendixHwe w

    explain how to print dvifiles properly.

    There are many options to the lprcommand that we have not covered.Yo

    should execute the command line

    %man lpr

    to learn more about it.When you do,you will notice many related commansuch as lprmand lpq.We cover these commands in Chapter 9.

    On many systems you have to acquire some local knowledge to be able t

    print effectively.For example,you will need to obtain the names ofthe local prin

    ers, information about how to process various types offiles, information abou

    printingquotas,and which print commands are available.This information is usu

    ally posted near the printers or online.Other users or the system administrato

    will usually be happy to share printinginformation with you.

    Exercises

    1. On your Unixsystem,what is the command line for printingthe

    file homeworkon the default printer?Is more than one printer

    available to you?What would the command line be for sendingthe

    file homeworkto a printer named laserwriter?

  • 8/10/2019 Grep and UNIX

    17/24

    55

    2. You will need to read the man pagefor lpror lpto complete

    thisexercise. How do you print five copiesofa document without

    repeatingthe print command five times?

    3. What doesthe word duplexmean?Can you print in a duplexstyle?If

    so,what isthe command for doingthis?

    4.A

    re thereprintin

    gquota

    son

    your

    system?

    Ifso,de

    scribe the

    mand

    explain how theyare enforced.

    4.7 Creating a Directorymkdir Command

    In order to properly organize your work,you will want to be able to create

    subdirectories. To create a subdirectory,you use the mkdir command. The

    command name is an abbreviation for make directory. You supply the

    subdirectoryname asan argument to the mkdircommand,and a subdirectorywill

    be made in the current workingdirectory. For example,to create a subdirectory

    in the workingdirectorycalled datafiles,you enter the command line%mkdir datafi les

    You can check that the directory datafiles was created by performing an ls

    command. To begin working in the directory,you can execute a cddatafiles

    command.

    Directoriescan be nested so you could create subdirectoriesofsubdirectories

    of subdirectories,and so on. In practice,personal subdirectories that are more

    than five or sixlevelsdeepbecome cumbersome.

    Ifyou are workingin a directorythat hasa growingnumber offiles,say20or

    more,you maywant to thinkabout organizingsome ofthe filesinto a subdirec-tory. It isa good idea to have a number ofsubdirectoriesset up in your home

    directory. When you login,you can then switch to the directorywhere you want

    to work.

    You should execute the command line

    %manmkdir

    to learn more about the mkdircommand.

    Exercises

    1. Create a subdirectorycalled testin your home directory.Move into

    the directory. Can you create another directorycalled testinside of

    the original directorytest?Tryit and cdto the latest test. What is

    the result ofexecutinga pwdcommand?

    4.7Creating a Directorymkdir Command

  • 8/10/2019 Grep and UNIX

    18/24

    Chapter 4Top Ten Most Useful Unix Commands

    56

    2. Can you create a subdirectory called VERYLONGNAMEDIREC

    TORY?

    3. Aman named Walter has 300files in his home directory and no

    subdirectories. What are some ofthe problems Walter faces when

    tryingto locate one ofhis files?

    4. For this problemdo not count hidden directories. Howmany directories in total would you have ifyou created directories five levels

    deepand had five subdirectories (not includinghidden directories)

    in every directory?

    4.8 Copyinga Filecp Command

    There are many times when you will want to copy a file. For example,

    * when you want to create a local backupversion ofa file.

    * when you want to create a duplicate version ofa file for test purposes.

    * when you want a local copy ofa file so you can edit it.* when you are beginningworkon a newfile and have a similar one that serv

    as a good startingpoint.

    The cpcommand is used to copy a file. The command name cpis an abbrevi

    tion for copy.When you copy a file,you simply create a distinct exact duplica

    ofthe file. This is different fromrenaminga file. We cover renamingfiles in Se

    tion 4.9.

    Warning:Ifyou tell Unixto overwrite an existingfile usingthe cpcomman

    it will. Be careful not to destroy the contents ofa file you want to keepby acc

    dently overwritingit withthe cpcommand.

    The cp command typically takes two arguments. The first argument is th

    name ofthe file you want to copy and the second argument is the name ofth

    copy. Ifyouwant to make a copy ofthe file important.notescalledNOTES,yo

    enter the command line

    %cp important.notes NOTES

    This command copies the file important.notes to the file NOTES.

    the file NOTES previously existed, it is overwritten with the contents

    important.notes. The original contents ofNOTESis lost. Ifthe fileNOTESd

    not exist,it is created and has the same contents as important.notes. To veri

    that the file was copied,you can execute the lslcommand and notice that bot

    files exist and have the same size.

    There are timeswhen youwant to copy all files fromone directory to anothe

    Suppose you want to copy all files fromthe current workingdirectory to its sub

    directory called BACKUP. The followingcommand line accomplishes this task

  • 8/10/2019 Grep and UNIX

    19/24

    57

    %cp * BACKUP/.

    Regardless of how many files there are in the current working directory, this

    simple command copies them all to the directory called BACKUPand preserves

    their names.The *means match all file names in this directory.The first part

    of the second argument tells the system the copies of the files are to be put in the

    (already existing)directory called BACKUP;the.

    tells the system that each file isto be given the same name that it had originally;the /is needed to separate the

    directory name BACKUPfrom the ..

    The usage of the cpcommand can be displayed by typing cpwithout any

    arguments.You should execute the command line

    %mancp

    to learn more about the cpcommand.

    Exercises

    1. What is the command for making a copy of the file called equip-

    ment?

    2. Describe two interesting options to the cpcommand.

    3. Suppose you want to copy all files from a directory called SYSTEM

    to a directory two levels up called Test.What command line could

    you use to achieve this?

    4. Create a test file called junk.What happens if you try to copy junk

    to itself?

    5. Is there a command for copying an entire directory hierarchy that is

    multiple levels deep?If so, describe it. 6. What is a command to copy all files with a txtfile extension from the

    current working directory to a child subdirectory called Text?

    4.9 Renaming a Filemv Command

    There will be many times when you want to rename a file.For example,

    * when you copy a file from the Webor a friend, and decide you have a better

    name for it.

    * when the contents of a file changes significantly.

    * when you realize a different descriptive name is more appropriate.* when you want to conduct a series of tests using a file and so decide to give it

    a very short name to save typing time.

    The mvcommand is used to rename a file.The command name mv is an

    abbreviation for move.When you rename a file, you simply change the name

    4.9Renaming a Filemv Command

  • 8/10/2019 Grep and UNIX

    20/24

    Chapter 4Top Ten Most Useful Unix Commands

    58

    of the file. The contents of the file are not altered. This is a different process fro

    copying a file. We covered copying files in Section 4.8.

    Warning:If youtell Unixto overwrite an existing file using the mvcomman

    it will. Be careful not to destroy the contents of a file youwant to keep by acc

    dently overwriting it with the mvcommand.

    Themv

    command typically takes tw

    o arguments. The first arg

    ument is th

    name of the file youwant to rename and the second argument is its newname. T

    rename the file black.shoesto brown.shoes,youenter the following comman

    line:

    %mv black.shoes brown.shoes

    After entering this command,the file black.shoesno longer exists,and the fi

    brown.shoescontains the exact same content that the file black.shoesused t

    contain.

    There are times when you want to move all files from one directory t

    another. Suppose youwant to relocate all files from the current working diretory to its child subdirectory called VERSION-2. The following command lin

    accomplishes this task:

    %mv *VERSION-2/.

    Regardless of how many files there are in the current working directory, th

    command moves them all to the directory called VERSION-2 and preserv

    their names. The *means match all file names in this directory.The first pa

    of the second argument tells the system the files are to be moved to the (alread

    existing)directory called VERSION-2;the .tells the system that each file is t

    be given the same name it had originally;the /is needed to separate the directoname VERSION-2from the ..

    The usage of the mvcommand can be displayed by typing mvwithout an

    arguments. Youshould execute the command line

    %man mv

    to learn more about the mvcommand.

    Exercises

    1. What is the command for changing the name of a file called glasses

    to wine.glasses?

    2. Create a test file called foo. What happens if youtry to rename a file

    that does not exist to foo?

    3. Describe two interesting options to the mvcommand.

  • 8/10/2019 Grep and UNIX

    21/24

    59

    4. Suppose you want to move all files from a directory called SEWING

    to a directory three levels up called CHORES. What command line

    could you use to achieve this?

    5. Create a test file called junk. What happens if you try to rename

    junkto junk?

    6.H

    ow could you use themv

    command to delete allbut one file in

    a directory?

    4.10 Deleting a Filerm Command

    There will be many times when you want to delete a file. For example,

    * the file is no longer needed.

    * you are runninglow on diskspace.

    * you copied it to another file and now only want to keep the new version.

    The rmcommand is used to delete a file. The command name rmis an abbre-

    viation forremove.

    When you remove a file,you delete it.

    Warning:If you tell Unixto delete a file usingthe rmcommand,it will. Be

    careful not to delete a file you want to keep. Once you have deleted a file,you

    cannot get it back.

    To delete the file velvet from the current workingdirectory,you enter the

    followingcommand line:

    %rm velvet

    If you execute an lscommand after deletinga file, the file you deleted will no

    longer be listed. There is no undelete command,so you cannot undo a mistake.

    There is also no recycle binfrom whichyou can retrieve the file;the file is reallygone.

    Sometimes you may want to delete all files that end in a certain file extension.

    The followingcommand line would delete all files in the current workingdirec-

    tory whose file extension is dvi:

    %rm *.dvi

    The followingcommand would delete all dvifiles,logfiles,and auxfiles:

    %rm *.dvi*.log*.aux

    As this example illustrates, t

    herm

    command can take several arguments.

    Note:The arguments are separated by spaces,not commas.

    Warning:If you tell Unixto delete a group of files usingthe rmcommand,

    it will. Be careful not to delete files you want to keep. Be very careful when using

    the rmcommand withan argument involving*.Once you have deleted a group

    of files,you cannot get them back.

    4.10Deleting a Filerm Command

  • 8/10/2019 Grep and UNIX

    22/24

    Chapter 4Top Ten Most Useful Unix Commands

    60

    Once in a while you will want to delete all files that begin with a certain pa

    tern. For example, you may want to delete all files that have the first two letters h

    However, before you decide to delete these files, it may be worthwhile to execu

    the command

    %ls he*

    in order to determine exactly which files will be deleted. Maybe you forgot th

    the file help, which you wanted to retain, was located in this directory. Ifyou a

    sure you want to delete all files beginning with he, you can execute the comman

    line

    %rmhe*

    The ioption to the rmcommand asks you whether you are sure you wan

    to delete a file before it is actually removed. The istands for inquiry. The ifla

    is recommended for beginning users, as it can prevent unwanted file deletion

    Some users and system administrators redefine the command rmto be rmi. Th

    can be accomplished using the aliascommand, which we cover in Chapter 6, b

    executing the command line

    %alias rmrm-i

    This way whenever an rmcommand is executed, the user has the option not t

    delete the file. Here is a concrete example:

    %rm-iponytail

    rm:remove ponytail (yes/no)?

    Ifyou enter an n, the file is not deleted. To delete the file, simply enter a y.

    You should execute the command line

    %manrm

    to learn more about the rmcommand.

    Exercises

    1. Write a command line to delete the files a, a1, and a2.

    2. Describe two interesting options to the rmcommand.

    3. How could you delete all the files in the current working directory?

    4. How could you delete an entire hierarchy offiles?

    5. How could you delete all files that have a file extension ofbak?

  • 8/10/2019 Grep and UNIX

    23/24

    61

    4.11 Deleting a Directoryrmdir Command

    Once you begin creating files and directories, you will find yourself in a situation

    where you want to do some reorganization. In such a situation you may find

    that you want to delete a directory. The rmdircommand, an abbreviation for

    remove directory,deletes a directory. When you remove a directory, you delete

    the directory.Warning:If you tell Unixto delete a directory using the rmdircommand, it

    will, but only if the directory is empty. Be careful not to delete a directory you

    want to keep.

    To delete the directory cellphone from its parent directory, you enter the

    command line

    %rmdir cellphone

    If the directory is empty, it will be deleted. Otherwise, you get a message such as

    rmdir:directorycellphone:Directorynotempty

    To delete a directory that is not empty, you can use the ror Rflag. Before

    using this flag, make sure you really want to delete everything in the directory.

    Once you delete the material, it is irretrievable. Sometimes you will want to delete

    a directory and all of its subdirectories. The ror Rflags can be used to recur-

    sively delete an entire directory hierarchy.

    You should execute the command line

    %man rmdir

    to learn more about the rmdircommand.

    Exercises

    1. Compare and contrast the two commands mkdirand rmdir.

    2. Describe two interesting options to the rmdircommand.

    3. What command could you use to delete the entire file structure

    contained beneath and including the directory GrayBeard?

    4. What happens if you try to delete a nonexistent directory?

    4.12 Clearing the Screenclear Command

    Sometimes after performing a mancommand and then quitting morewith q,

    your screen may have become cluttered. It might be difficult to separate the

    results of the next command you enter from those of the previous one. Since

    output on the screen simply scrolls up, you may sometimes find it desirable to

    start with a fresh screen. Unixprovides the command clearfor this purpose.

    4.12Clearing the Screenclear Command

  • 8/10/2019 Grep and UNIX

    24/24

    Chapter 4Top Ten Most Useful Unix Commands

    The command line

    %man clear

    yieldsa NAMEsection of

    NAME

    clear -clear the terminal screen

    We see thattyping

    %clear

    clearsthe screen forusand displaysthe Unixpromptat the topofthe scree

    Suppose youperform an lscommand and obtain the followingresult:

    GENERALS conclu.tex normscite.sty summary.tex

    README depth.tex outline.tex thesis.bib

    abstract.tex examples.tex prelims.tex thesis.tex

    backgrd.tex intro.tex report.sty uwthesis.sty

    bib.tex model.tex slides zoo.tex

    breadth.tex myalpha.bst subgraph.tex

    Youthen decide to delete the file zoo.tex,so youenterthe command line

    %rm zoo.tex

    Nowyouwant to verify thatzoo.texhasbeen deleted, so youdo another l

    resultingin the followingdisplay:

    GENERALS conclu.tex normscite.sty summary.tex

    README depth.tex outline.tex thesis.bib

    abstract.tex examples.tex prelims.tex thesis.tex

    backgrd.tex intro.tex report.sty uwthesis.sty

    bib.tex model.tex slides

    breadth.tex myalpha.bst subgraph.tex

    Ifyoucontinued to delete individual filesin thisfashion and then checked to see

    theywere gone,eventuallythe screen would become cluttered.Atthatpointyo

    mightdecide to use clear,asitwill be easierto read youroutputon a fresh scree

    In such circumstances,youwill find the clearcommand veryuseful.

    Exercises

    1. Execute the command manclearon yoursystem.Howmanyscreen

    fulsofinformation did youget?Are there anyargumentsto the clea

    command?Any

    related commands?

    2. Ifyouare usinga GUIwith yourversion ofUnix,whatisthe effect

    ofclearingthe screen?Once youclearthe screen,are youstill able t

    retrieve itsformercontents?

    3. Give two reasonswhyyoumightwantto clearthe screen.