Filename Completion in the C Shell - PowerPoint PPT Presentation

1 / 142
About This Presentation
Title:

Filename Completion in the C Shell

Description:

csh will complete file names for if the filec shell variable is set. set filec ... d - display error message rather than ringing bell if an illegal command is used ... – PowerPoint PPT presentation

Number of Views:75
Avg rating:3.0/5.0
Slides: 143
Provided by: jack86
Category:

less

Transcript and Presenter's Notes

Title: Filename Completion in the C Shell


1
Filename Completion in the C Shell
  • csh will complete file names for if the filec
    shell variable is set
  • set filec
  • Just type first part of name and press ltESCgt key
  • Example
  • mikey ls
  • jerry john joe jimmy wesley tom
  • bill willie ken ted shirley joan
  • mikey more je ltESCgt
  • mikey more jerry shell types rest of name

2
Filename Completion Examples
  • mikey ls
  • jerry john joe jimmy wesley tom
  • bill willie ken ted shirley joan
  • mikey cat joltESCgt
  • cat johltESCgt
  • cat john
  • mikey cat joltESCgt
  • cat joltDgt
  • john joe joan
  • cat jo

3
Filename Completion
  • If the prefix is ambiguous, the shell cant read
    your mind so it completes as much as it can and
    beeps
  • You can then indicate what file you want, hit ESC
    again and the filename will be completed
  • Or, you can type CTRL-D and the shell will list
    all possible matches

4
conCATenate file(s) - cat
  • Concatenate files to standard output
  • Syntax cat -benstuv filename...
  • b - number all lens except blanks
  • e - display non-printing characters and at
    end-of-line
  • n - number all lines

5
conCATenate file(s) - cat
  • s - substitute a single blank line for multiple
    adjacent blank lines
  • t - display non-printing and tab characters
  • u - unbuffered

6
Word Count - wc
  • Display a count of lines, words, and characters
  • Syntax wc -lwc filename ...
  • l - count lines
  • w - count words
  • c - count characters
  • Example
  • mikey wc testfile
  • 7 43 168 testfile
  • mikey

7
Neat cat Tips
  • cat filename1 filename2 gt filename3 creates a new
    file, filename3 that consists of the contents of
    filename1 followed by the contents of filename2
  • cat gt filename1 creates a new file named
    filename1 whose contents are whatever you type on
    the keyboard
  • mikey cat gt my_file
  • The cat in the hat
  • smiled back at me.
  • d (end-of-file character)
  • mikey

8
more
  • Page through a text file
  • Syntax more -cdflsu -lines linenumber
    /pattern filename...
  • c - clear screen before displaying
  • d - display error message rather than ringing
    bell if an illegal command is used
  • f - do not fold long lines
  • l - do not treat formfeed characters as page
    breaks
  • s - squeeze multiple adjacent blank lines into
    one
  • u - suppress underlining escape sequence

9
Commands for more
  • v - drop into vi at the current line
  • i/pattern - serach for the ith occurrence of
    pattern
  • h - help, gives list of commands
  • !command - invokes a shell to execute command
  • . - repeat last command
  • q or Q - exit from more

10
head
  • Display the first few lines of a specified file
  • Syntax head -n filename...
  • -n - number of lines to display, default is 10
  • filename... - list of filenames to display
  • When more than one filename is specified, the
    start of each files listing displays
  • gtfilenamelt

11
tail
  • Displays the last part of a file
  • Syntax tail -number lbc f filename
  • or tail -number l rf filename
  • number - begins copying at distance number from
    beginning of file, if number isny given,
    defaults to 10
  • -number - begins from end of file
  • l - number is in units of lines

12
tail
  • b - units are blocks
  • c - units are characters
  • r - print in reverse order
  • f - if input is not a pipe, do not terminate
    after end of file has been copied but loop. This
    is useful to monitor a file being written by
    another process

13
touch
  • Update the access and modification times of a
    file
  • Syntax touch -c -f filename ...
  • -c - Do not create filename if it doesnt exist,
    default
  • is to create filename
  • -f - Attempt to force the update in spite of
    read/write permissions associated with
    filename
  • Why would you want to do this?
  • This is particularly useful in software
    development

14
File System
  • Unix provides a hierarchical, or tree-like, file
    system
  • Supports two main objects
  • Files
  • Directory files, or directories
  • From Unixs view, there is no difference between
    the two
  • From the users view, files are data that you
    want, directories are containers of files
  • In reality, files are simply a stream of bytes
  • Critical design philosophy of Unix

15
Tree Structure
16
Files and Directories
17
File Names
  • Every file has a filename
  • Current versions of Unix allow up to 255
    characters, older versions limit to 14

18
File Names
  • Almost any character can be used in a filename
  • Sticking with the following will save many
    problems
  • Uppercase letters (A-Z)
  • Lowercase letters (a-z)
  • Numbers (0-9)
  • Period ( . ) can be used as any other character
    and may denote special files
  • Exception is the root directory, which is always
    named /
  • No other file can use this name
  • Comma ( , )
  • Dash ( - )
  • Underscore ( _ )

19
Other File Name Rules
  • Other characters may be used by escaping them
    with a \ character
  • Willie\Weasil - displays as WillieWeasil
  • Much confusion can result from this
  • File names are case sensitive
  • my_file, My_File, and MY_FILE are all unique names

20
File Access Controls
  • Unix provides file security with access levels
    and permissions
  • Access levels define who specific permissions
    belong to
  • user (u)
  • group (g)
  • other (o)

21
File Access Controls
  • Unix provides file security with access levels
    and permissions
  • Access levels define who specific permissions
    belong to
  • user (u)
  • group (g)
  • other (o)

22
Access Controls Provide Security
  • Generally accepted that there are files users
    cannot access or modify
  • This provides security for
  • System
  • Work groups
  • Individual users

23
MaKe DIRectory - mkdir
  • Creates new directories
  • Syntax mkdir -p dirname
  • p - allows missing parent directories to be
    created as needed
  • Requires write permission in the parent directory

24
ReMove file(s) - rm
  • Removes (deletes) files
  • Syntax rm - -fir filename ...
  • - Treat following arguments a filenames, so you
    can remove files starting with a minus sign
  • f - Force files to be removed without displaying
    permissions, asking questions, or reporting
    errors
  • i - Interactive, ask before removing each file
  • r - Recursively delete the contents of a
    directory, its subdirectories, and the directory
    itself

25
ReMove DIRectory - rmdir
  • Removes empty directories
  • Syntax rmdir directory...
  • An error will be reported if the directory is not
    empty

26
LiSt directory - ls
  • List the contents of a directory
  • Syntax ls -aAcCdfFgilLqrRstu1 filename
  • a - List all entries, without this, files
    beginning with a . are not listed
  • c - Sort on time of last edit
  • l - List in long form, giving mode, number of
    links, owner, size, and time of last
    modification
  • R -Recursively list subdirectories encountered
  • s - Give size of file in kilobytes
  • t - Sort by time modified, latest first

27
Change Directory - cd
  • Change current working directory
  • Syntax cd directory
  • Without argument, changes to your login directory
  • Otherwise changes to directory

28
Print Working Directory - pwd
  • Display pathname of current working directory
  • Syntax pwd

29
Absolute Pathnames
  • Every file has a pathname
  • A pathname is built by tracing a path from the
    root directory, through all intermediate
    directories, to the file
  • String all the filenames in the path together,
    separating them with slashes ( / ) and proceeding
    them with the root directory ( / )
  • Example /usr/src/cmd/date.c

30
Path Names
31
Relative Pathnames
  • Every directory has two intrinsic directories
  • . (this directory)
  • .. (the parent directory)
  • These make using relative pathnames easy

32
inode
  • inodes (or index nodes) contain information about
    files
  • inodes do not contain path or file name
    information

owner tanjs group 567 type regular
file permissions rwxr-xr-x last accessed Aug 23
2003 145 PM last modified Jul 4 2004 917
AM size 6030 bytes number of links 2 disk
addresses
33
LiNk - ln
  • Create a pseudonym for an existing file
  • Syntax ln -fs filename linkname
  • f - force a hard link to a directory, only
    available to
  • supersuser
  • s - create a symbolic (soft) link

34
LiNk - ln
  • Hard links are default, they create a pointer to
    the file
  • Symbolic, or soft links, create an indirect
    pointer to the file via the pathname
  • Although only the superuser can create a hard
    link to a directory, any user can create a soft
    link
  • Soft links also work across file systems

35
Why Hard and Soft Links?
  • Hard links all have equal status
  • When a file with hard links is deleted, the
    actual file remains until all of the hard links
    have been deleted

36
Why Hard and Soft Links?
  • Soft links can have the original file deleted
    while soft links still remain
  • Soft links can also be confusing when used to
    change directories
  • Suppose you have a soft link called My_Dir that
    points to your home directory, /home/tanjs and
    you cd My_Dir
  • Then, if you execute pwd, it shows /home/tanjs!
  • pwd shows the name of the linked-to directory
    rather than the name of the link

37
Why Not Just Make a Copy?
  • ln creates a pseudonym for the given file
  • No new inode is created
  • Only one copy of the actual file exists
  • Modifications via either filename affect the file
  • cp creates a new copy of the given file
  • A new inode is created
  • Twice as much disk space is used
  • Modifications to the copy are not reflected in
    the original

38
Metacharacters
  • Characters with special meaning to the shell
  • , ?, ...,
  • matches any grouping of zero or more characters
  • ? matches any single character
  • ... allows matching a range of characters
  • 0-9 matches any digit
  • A-Z matches any capital letter
  • a-d matches a, b, c, or d
  • aeiou matches any vowel

39
Metacharacter Examples
  • Suppose a directory listing of your files shows
    the following files
  • mikey ls
  • toy boy coy cow soy1
  • soy2 soy.1 soy1.1 bow mow1
    mow2
  • mow3 say1.1 say1.2 say1.3 hay shay
  • tray fray flay chow slay
    bay buy
  • How do we select groups of these files using
    metacharacters?

40
history
  • Display the history list in the C or Korn shells
  • Syntax history -hr n
  • h - display history list without leading numbers
  • used to produce files for input as a script
  • r - display the history list in reverse order
    with most recent command first

41
history
  • n - number of previous commands to display
  • if n is omitted, the entire history list is
    displayed where the entire list length is
    determined by the value of the shell variable
    history
  • Example
  • set history 40

42
Using history
  • History event specifiers
  • Always preceded by a ! (bang) this identifies
    the command as a history command
  • !! - Repeat previous command
  • !n - Repeat command n
  • !-n - Repeat the nth-to-last command

43
Using history
  • !str - Repeat the last command beginning with str
  • !?str? - Repeat the last command containing str
  • ! - Repeat the current command line typed
  • so far
  • Normally used with word designators to select
    portions of the current command line

44
history Examples
  • Recalling the last command
  • mikey lpr letter_to_Mom
  • mikey !!
  • lpr letter_to_Mom

45
history Examples
  • Referring to commands by number
  • mikey history
  • 1 ls
  • 2 cat letter_to_Mom
  • 3 lpr letter_to_Mom
  • mikey !2
  • cat letter_to_Mom

46
!-n Tip
  • mikey !-2 repeat format
  • cat -ms lettermore
  • mikey !-2 repeat edit
  • vi letter
  • mikey !-2 repeat format
  • cat -ms lettermore

47
Referring by Relative Number
  • mikey history
  • 1 ls
  • 2 vi letter_to_Mom
  • 3 cat letter_to_Mom more
  • 4 cat -ms letter_to_Mom lpr
  • mikey !-3
  • vi letter_to_Mom
  • mikey !-2
  • cat -ms letter_to_Mom lpr

48
Referring to Commands by Strings
  • mikey history
  • 347 who
  • 348 wc -l data
  • 349 cal 1776
  • 350 vim calendar
  • 351 vim datebook
  • mikey !w
  • wc -l data

49
Referring to Commands by Strings
  • mikey history
  • 347 who
  • 348 wc -l data
  • 349 cal 1776
  • 350 vim calendar
  • 351 vim datebook
  • mikey !wh
  • who
  • mikey !?datebook?
  • vim datebook

50
Command Editing with history
  • General form of substitution - !s/old/new/
  • mikey history
  • 347 who
  • 348 wc -l data
  • 349 cal 1776
  • 350 vim calendar
  • 351 vim datebook
  • mikey !350s/calendar/datebook/
  • vim datebook

51
Command Editing with history
  • A shortcut for the previous command
  • mikey datebookcalendar
  • vim calandar

52
Saving history Across Logins
  • If you set the savehist shell variable, the shell
    saves history lines in /.history at logout and
    reads them at the next login
  • If you set savehist without specifying a value,
    the entire history list is saved
  • set history 20
  • set savehist

53
Saving history Across Logins
  • If you give it a value, only that many events
    will be saved
  • set history 20
  • set savehist 10

54
PaGe - pg
  • Page through a file
  • Unlike more, pg allows you to back up in the file
  • After each screen is displayed, it pauses,
    displays a prompt, and awaits a command
  • Perusal commands
  • Return or Enter - display next screen
  • (-)number - simulate scrolling forward or
    backwards number of screens
  • . or CTRL-L - redisplay current screen

55
Searching with pg
  • i/pattern/ - search forward for the ith
    occurrence (default i1) of pattern
  • ipattern or i?pattern? - search backwards
    for the ith occurrence (default i 1) of pattern
  • After searching, pg will normally display the
    line containing pattern at the top of the screen
  • h displays summary of commands
  • q or Q exits

56
CoPy file(s) -cp
  • Syntax cp -ip filename1 filename2
  • cp -rR -op directory1
    directory2
  • cp -iprR filename ...
    Directory
  • i - interactive, prompt for confirmation whenever
    the copy would overwrite an existing file
  • p - preserve, duplicate not only the file
    contents but also modification time and
    permission modes

57
CoPy file(s) -cp
  • r or R - recursive, if any of the source files
    are directories, copy the directory along with
  • its files, including any subdirectories and
  • their files

58
Forms of cp
  • cp -ip filename1 filename2
  • copies filename1 onto filename2
  • cp -rR -op directory1 directory2
  • recursively copies directory1, along with its
    contents and subdirectories, into directory2
  • cp -iprR filename ... directory
  • copies filename(s) into directory
  • Beware of a recursive cp like this
  • mikey cp -r /home/tanjs/src /home/tanjs/src/backu
    p
  • Why?
  • cp refuses to copy a file on top of itself

59
MoVe file - mv
  • Move or rename files
  • Syntax mv - -fi filename1 filename2
  • mv - -fi directory1 directory2
  • mv - -fi filename ... directory
  • - - interpret all following arguments as
    filenames. This allows filenames that begin with
    a minus sign
  • f - force, overriding mode restrictions and the
    -i option. Also suppress warning messages about
    modes that would restrict overwriting

60
MoVe file - mv
  • i - interactive, displays the name of the file or
    directory with a ? if the move would overwrite an
    existing file or directory

61
cp Versus mv
  • mv simply changes the filename or absolute
    pathname of the affected files, the files inodes
    are not changed
  • cp creates new files so new inodes are created,
    unless the copy is overwriting an existing file

62
ed Editor
  • ed is a simple line editor
  • Line editor implies that the unit of change is
    one line at a time
  • Its origin is the teletype, the only terminal
    available at the time
  • Teletypes are inherently line oriented

63
ed Editor
  • Syntax ed -s -p string filename
  • s - suppress printing of character counts,
  • diagnostics, and the ? prompt when quitting
  • without saving
  • p string - use string as the editing prompt in
  • command mode

64
Why Learn ed?
  • Wherever you go, on whatever Unix system you use,
    you will find ed
  • It is easy to learn and remember the basic steps
    of ed for simple file creations and edits
  • ed introduces regular expressions, one of Unixs
    true power tools, which are used in many Unix
    utilities
  • ed forms the basis of other editors so things you
    learn with ed will transfer to other editors
  • Even if you have messed up your terminal
    descriptor (stty file) you can still perform
    edits with ed

65
ed Architecture
  • ed does all his work in memory in a buffer
  • Your file is not affected by anything you do
    until you perform a w (write) command
  • This means you can back out of changes easily by
    quitting ed without writing your edits
  • It also means you can lose all your work if you
    forget to save (write) your edits
  • ed will attempt to remind you (if you let it) if
    you try to quit without saving

66
Starting with ed
  • mikey ed dolby.txt
  • ?dolby.txt No such file or directory
  • a
  • Now is the time for all
  • good men to come to the
  • aid of their country.
  • ltDgt Terminate ed session
  • ? ed prompt
  • w
  • 70 Character count
  • q
  • mikey

67
ed Modes
  • ed is modal, that is, there is a text input mode
    and a command mode
  • Text mode interprets all input as text
  • Command mode interprets all input as commands
  • Command mode can display a prompt, either a
    custom prompt with the -p string option on
    startup or the default () with the P command
  • Text input mode displays no prompt
  • Text input mode is entered by using a (append) or
    i (insert) and exited by a . (period) as the
    first (and only) character on a line

68
Error Messages in ed
  • ed is a very terse environment
  • The default error message is ?
  • Entering an h after an error will give a more
    descriptive, but still terse, error message for
    that specific error
  • Entering an H (in command mode) will turn on
    verbose error messages for all errors

69
Quitting ed
  • To quit ed, enter a q in command mode
  • If your file has not been saved since the last
    edit, ed will display an error
  • If you still want to quit without saving your
    file, enter q again
  • Otherwise, enter w or w filename to write (save)
    your file and then enter q
  • Q exits ed immediately, if you have not saved
    your file, all edits will be lost!

70
Line Numbering
  • All lines are numbered
  • p (print) lets you display lines
  • np will display the nth line if it exists
  • or a ? if it doesnt
  • p is assumed so a number by itself will display
    the line
  • 2 displays line 2

71
Line Numbering
  • Displaying ranges of lines
  • 1,3p displays lines 1, 2, and 3
  • 4,12p displays lines 4 through 12
  • 5,5p displays line 5

72
More Line Numbering
  • has special meaning to ed
  • last line
  • p displays last line of buffer
  • 1,p displays all lines in buffer
  • n is a variant of p that displays line numbers

73
More Line Numbering
  • Line numbers and are known as addresses
  • General form for many ed commands is
  • address1, address2command_letter(s)
    filename
  • where the default command_letter is usually p
  • filename is only used with read and write commands

74
Address in ed
  • You always have a current address in ed
  • All edits are referenced to the current address
  • There are several special address symbols in ed
  • represents the last line in the buffer
  • . period, represents current line
  • , address range (1,5 is lines 1 through 5)
  • address range . - (current line through
  • last line in the buffer)
  • digit any digit will make that line the current
  • address and print it

75
Moving Around in ed
  • The easiest way to move around a file in ed is to
    enter the line number you want to go to
  • This will display the line and make it your
    current address

76
Moving Around in ed
  • Relative addressing also works
  • To go to the third line before the current line,
    enter -3
  • To go to the tenth line following the current
    line, enter 10
  • Note, these are shorthand versions of .-2 or .10
    which represents the current line -2 or the
    current line 10

77
Oops, I Made a Mistake!
  • ed allows you to undo edits
  • This is done using the u command
  • This only works on the last edit performed and
    does not work across file saves
  • If you do another edit or command that changes
    the buffer, you lose the ability to undo the
    previous edit
  • You can even undo an undo!

78
Adding Text
  • Adding text is done by either inserting lines or
    appending lines
  • Insert (i) places a line in front of the current
    line
  • Append (a) places a line after the current line
  • Since an empty file has no lines, you must start
    a new file creation with append since insert puts
    a new line before the current line and there are
    no lines yet

79
Patterns and Searches
  • Searching is also a powerful way to move about in
    ed
  • The two common forms of searches are forward
    searches and backwards searches
  • /expr/ denotes a forward search
  • ?expr? denotes a backwards, or reverse search

80
Patterns and Searches
  • Searches stop when they find the first occurrence
    of expr (expr is often a regular expression)
  • When the search is successful, it displays the
    line and makes it the current line
  • Preceding the search with a g (global) searches
    and displays all lines containing expr - g/expr/

81
What Is a Regular Expression?
  • Regular Expressions are the power tools of Unix
  • They allow you to specify an expression that
    matches a pattern rather than a specific string
  • A regular expression is a sequence of
  • ordinary characters
  • special, or metacharacters

82
ed Special Characters
  • \ is an escape character that allows you to use
    the other special characters as regular
    characters
  • represents a set of zero or more characters
    where any one character is a match
  • represents the value of the match string for
    substitution commands

83
ed Special Characters
  • \ is an escape character that allows you to use
    the other special characters as regular
    characters
  • represents a set of zero or more characters
    where any one character is a match
  • represents the value of the match string for
    substitution commands

84
Sample Regular Expressions
  • aeiou matches any one of the vowels
  • z matches z, zz, zzz, or a z followed by any
    number of zs
  • stop matches stop only if stop is the last
    string on a line
  • 35z matches either 3, or 5, or z
  • \\ matches the string
  • i.m matches i followed by any character followed
    by m - iAm, or ibm, or i m, but not idiom

85
More Regular Expressions
  • A or inside are taken literally unless
    they are the first character following the ,
    then the search is logically inverted
  • T or T matches any character except T
  • icbm matches iam, i9m, or ixm, but not icm or
    ibm
  • icbm matches icm, ibm, or im and nothing else

86
More Regular Expressions
  • A or inside are taken literally unless
    they are the first character following the ,
    then the search is logically inverted
  • T or T matches any character except T
  • icbm matches iam, i9m, or ixm, but not icm or
    ibm
  • icbm matches icm, ibm, or im and nothing else

87
Deleting Lines of Text
  • d is used to delete lines of text
  • The format of the command is ,d where the
    represents line numbers and are optional
  • d by itself deletes the current line
  • 1,3d deletes lines 1 through 3
  • 3,7d deletes lines 3 through 7
  • .,d deletes the lines from the current line
    through the end of the buffer
  • 1,d deletes all lines in the buffer

88
Finding/Changing the Filename
  • If you forget the name of the file you are
    working on, the f command will display the file
    name
  • f new_filename will give the edit session a new
    filename. However, the buffer will not be saved
    in the new file until you issue a write command
  • If you start ed without a filename, the first
    command that uses a filename will set the current
    filename
  • After that, unlike many editors, such as MS-Word,
    reads and writes with different filenames will
    not alter the current filename

89
Combining Lines
  • To join lines, use the j (join) command
  • The j command requires the line numbers of two
    contiguous lines

90
Combining Lines
  • Examples
  • 1,2j combines lines 1 and 2
  • 10,11j combines lines 10 and 11
  • 10, 14j is an error because the lines are not
    contiguous
  • Note is there is no space at the end of the
    first line, there will not be a space between the
    last word of the first line and the first word of
    the second line which will have to be manually
    corrected

91
Moving Lines of Text
  • Moving lines is done using the m (move) command
  • m requires an optional range of addresses to move
    and a required address to move to.
  • Note that the lines are moved immediately behind
    the move to address

92
Moving Lines of Text
  • Examples
  • m4 moves the current line behind line 4
  • 1,3m moves lines 1 through 3 to the end of the
    file
  • m0 moves the current line to the beginning
  • m swaps the current line with the next line

93
Copying Text with Transfer
  • The t (transfer) command works similarly to the m
    command except it copies the source lines rather
    than moving them
  • t requires an optional range of addresses to copy
    and a required address to copy to.
  • Note that the lines are copied immediately behind
    the copy to address

94
Copying Text with Transfer
  • Examples
  • t. duplicate the current line
  • t copies the current line to the end of the
    buffer
  • 1,t duplicates the entire buffer at the end of
    the buffer
  • 1,t0 does the same only at the beginning of the
    buffer

95
Deleting Inserting with Change
  • The c (change) command deletes the line(s) given
    by the address range and then replaces them with
    typed text
  • Normal form is ,c where is a line address
  • Example
  • 1,3c deletes lines 1,2, and 3 and then takes
    whatever is typed and inserts it
  • Note the change command deletes a given number
    of lines but replaces them with whatever you
    type. That be be the same number of lines, or
    more or fewer.

96
Substitutions
  • Since ed is a line editor, the line is the unit
    of change
  • The change command is fine when a line requires
    extensive modification
  • The s (substitute) command provides a way to
    change parts of a line without deleting and
    retyping the entire line

97
Deleting Inserting with Substitute
  • The format for s (substitute) is
  • ,s/find_expr/repl_expr/gn
  • , is an address range, default is current line
    only
  • find_expr is the search string
  • repl_expr is the string that replaces the search
    string

98
Deleting Inserting with Substitute
  • g is a global option, meaning to replace all
    occurrences within the address range (default is
    first occurrence)
  • n is an option to replace the nth occurrence in
    each line
  • find_expr is often a regular expression

99
Substitution Examples
  • s/sun/moon/ will replace the first occurrence of
    sun with moon on the current line only
  • 1,5s/sun/moon/ will do the same but for lines 1 -
    5
  • 1,5s/sun/moon/g will replace all occurrences of
    sun with moon in lines 1 through 5
  • 1,s/sun/moon/g will replace all occurrences of
    sun with moon in the entire buffer

100
Substitution Examples
  • The metacharacter can be used for complex
    substitutions
  • s/ sun/ and moon/ replaces sun with sun and
    moon
  • Note the value of the current address is set to
    the last line that produces a match

101
Marking Lines
  • Lines that you want to be able to refer to easily
    can be marked using the k command
  • addresskx
  • where address is an optional line address,
    default is current line
  • x is any lower case letter
  • Once a line is marked, you can use x at any time
    as an address argument without having to know the
    actual line number

102
Line Marking Example
  • /sun/ka marks the next line containing sun as a
  • /moon/kb marks the line containing moon as b
  • a,bp displays the marked block
  • a,bm moves the marked block to the end of
    the buffer
  • a,bd deletes the marked block
  • u restores the block

103
Reading Files
  • Reading a file inserts the file into the buffer
    following the given line address, default is ,
    the end of the buffer
  • 0r filename is used to insert file at the
    beginning
  • The current address is set to the last line of
    the file
  • Format is addressr filename
  • Example
  • 8r test.txt inserts the file test.txt
    immediately following line 8 and makes the
  • current line (.) the last line of test.txt

104
Changing Edit Files
  • During the course of editing, you may want to
    change edit files without leaving ed
  • The edit (e) command allows you to do this
  • Format is e filename or E filename
  • both commands delete your current buffer and load
    it with the new file
  • if the buffer has been changes since the last
    write, e will prompt with a ? before deleting the
    buffer, E will silently just delete it

105
Escaping to the Shell with !
  • The ! (bang) symbol will allow you to run a shell
    command from within ed
  • In command mode, type ! command and the command
    will be executed
  • Example
  • !ls will spawn a shell, display your file
  • list, and return to ed

106
The vi Editor
  • Uses ed commands
  • Not a line editor

107
Recovering a Buffer
  • If the system goes down during an edit session,
    vi will attempt to save your current edit buffer
  • On your next login, enter vi -r and vi will list
    any edit buffers the system has saved
  • To recover any of these buffers, use vi -r
    filename to reload the saved buffer
  • You can force the system to preserve your current
    edit buffer by using pre although there usually
    isnt a good reason to do this

108
Customizing vi Using Options
  • vi can be customized using set commands
  • Two kinds of set commands exist
  • Toggles, which are either On of Off
  • Options which take values or strings
  • Toggles are activated/deactivated by
  • set option to turn option On
  • set nooption to turn option Off
  • Value options are set using
  • set optionvalue or set optionstring

109
Viewing Current Options
  • set all will display a complete list of current
    options, both those set by you and those that are
    defaulted by vi
  • set option? displays the current value of option
  • set shows options that either you set during the
    edit session or were set via your .exrc file

110
Some Useful Options
  • wrapmargin (wm) - causes vi to automatically word
    wrap text as you type
  • value gives minimum distance from right margin
  • Three options that control searching
  • noignorecase (noic) - differentiates between
    upper and lower case
  • wrapscan (ws) - wraps around the beginning or end
    of edit buffer during searches
  • magic (magic) - recognizes wildcards (., . )
    in searches

111
Options Useful for Programmers
  • autoindent (ai) - in insert mode, indents each
    line to the same level as the one above it
  • showmatch (sm) - when ) or is entered, vi
    momentarily moves to matching ( or
  • tabstop (ts) - defines number of spaces that a
    TAB produces
  • shiftwidth (sw) - defines number of spaces in
    backwards TAB (Ctrl-D) when using autoindent
  • number (nu) - displays line numbers when editing
  • list (list) - displays TABs as I, marks end of
    lines with

112
.exrc File
  • When vi starts, it reads the .exrc file in your
    home directory, if it exists
  • Use this file to customize vi with any options,
    abbreviations or key-command maps you always want
    to use
  • An example .exrc file might look like this
  • set wm10
  • set exrc
  • ab nlcc North Lake Community College
  • set autowrite

113
Alternate Environments
  • vi will also read a .exrc file in your current
    directory
  • This is useful if you want vi to behave
    differently for specific projects, such as C or
    lisp programming

114
Alternate Environments
  • Example for C programming
  • set nu
  • set autoindent
  • set ts3
  • set shiftwidth3
  • set showmatch
  • You can also read a file of options at anytime
    using so filename

115
Using the Named Deletion Buffers
  • The last 9 deletions are stored in numbered
    buffers from 1-9
  • Only major deletions, small deletions, such as
    characters or parts of lines can only be restored
    by using a p command immediately after the
    deletion
  • To recover a deletion, enter np where n is the
    number of the deletion you want to recover
  • 2p would be the second-to-last deletion, 4p
    would be fourth from last, etc.

116
What if I Dont Know Which Buffer?
  • If you dont know which buffer contains the
    deletion you want, vi will cycle through them for
    you
  • 1pu.u.u etc
  • This inserts the last deletion, undoes the
    insert, and the . (period) advances to the next
    buffer and inserts it

117
Using Named Buffers for Copies
  • When copying text you want to use multiple times,
    named buffers can be used
  • There are 26 named buffers (a-z)
  • To use a named buffer, precede the yank or put
    command with a and the buffer name
  • xyy Copy current line into named buffer x
  • xP Put text from named buffer x before
    cursor

118
Copying Text Between Files
  • vi file1
  • Copy desired text to a named buffer
  • a6Y
  • e file2
  • Paste your text into the new file
  • ap
  • w and save your changes
  • If you want, you can then switch back and forth
    between file1 and file2 using
  • e

119
Filtering Text Through a Shell Cmd
  • Text is filtered through a command shell by
    entering an ! followed by any vi movement command
    that indicates a full line or more of text
    followed by the Unix command

120
Filtering Text Through a Shell Cmd
  • This command sequence has some oddities
  • The ! doesnt appear until you type the text
    object reference, and then it appears at the
    bottom of the screen but the object reference
    doesnt display
  • The text object must be more than one lines
  • There is a special text object available, !,
    which indicates the current line
  • To repeat the previous command, enter ! object !

121
Abbreviations
  • You can define shortcuts, or abbreviations for
    commonly used phrases in vi
  • set ab abbreviation phrase
  • Example
  • set ab ibm International Business Machines
  • These can then be used in insert mode
  • Example
  • iThe ibm corporation
  • will expand to
  • The International Business Machines corporation

122
More Abbreviations
  • To disable a previous abbreviation use
  • unab abbreviation
  • To list currently defined abbreviations
  • ab

123
More Abbreviations
  • The characters that compose your abbreviation
    cannot appear at the end of your phrase
  • ab IBM the corporation known as IBM
  • This will cause a recursion error, creating an
    infinite loop
  • Using the characters of your abbreviation within
    your phrase may or may not produce an error but
    is strongly discouraged

124
Mapping Frequent Commands
  • To save frequently used command sequences to a
    shortcut, use
  • map x sequence
  • unmap x will disable the sequence
  • map will display all currently mapped characters

125
Mapping Frequent Commands
  • To use map, you need to know the characters that
    arent used by vi in command mode
  • g K q V v _ \ Ctrl-A Ctrl-K Ctrl-O Ctrl-T
    Ctrl-W Ctrl-X
  • Example key mappings
  • map g dwelp will delete the current word (dw),
    move to the end of the next word (e), move right
    one space (l) and put the deleted word there (p).
    In other words, the mapping for g will reverse
    any two words.

126
Protecting Keys From ex
  • ENTER, ESC, BACKSPACE, DELETE, Ctrl-T, Ctrl-W,
    and Ctrl-X can only be used in a map or
    abbreviation if first escaped by Ctrl-V
  • Example
  • ab address 123 Floyd RdMPlano,TXM75243
  • M is what will display when you enter Ctrl-V
    ENTER
  • map T dwelp Ctrl-V Ctrl-T displays a T

127
Line Print - lp, cancel
  • lp arranges for the named files and associated
    information (called a request) to be printed on a
    line printer
  • cancel lp requests
  • Syntax lp -ddest -nnumber -ooption
    -ttitle filename
  • cancel ids
  • lp displays an id that identifies the print
    request
  • cancel uses this id to cancel a specific print
    request

128
lpr
  • lpr sends a job to the printer via the print
    spooler
  • Syntax lpr -Pprinter -copies -Ttitle -h
    filename
  • -P - desired printer as listed in /etc/printcap
  • - - number of copies
  • -T - title
  • -h - suppress burst page
  • filename - file to print
  • lpr has many more options and capabilities
  • See the man page for more info

129
Line Printer Queue - lpq
  • Displays the queue of printer jobs
  • Syntax lpq -Pprinter -l interval
    username...
  • -P printer queue to display, default is
    defined by environmental variable PRINTER,
    or system default printer
  • if PRINTER isnt set
  • -l display queue information in long
  • format

130
Line Printer Queue - lpq
  • -l display queue information in long format
  • interval displays the queue every interval
    seconds until queue is empty
  • username displays jobs for username(s)
  • Example of lpq output
  • Rank Owner Job Files
  • active tanjs 143 test.txt

131
Line Print ReMove - lprm
  • Remove files from the specified print queue
  • Syntax lprm -Pprinter - job
  • -P specifies which printer queue
  • - remove all jobs owned by you
  • job remove specified job numbers, or ids

132
Line Print ReMove - lprm
  • Example
  • lprm -Pps 144 removes job 144 from ps queue
  • lrpm -Pversatec - removes all my pending jobs
    from versatec queue
  • lprm 144 removes job 144 from default
    printer queue

133
file
  • Attempts to determine the type of a file by
    examining its contents
  • Syntax file -ffile -L filename
  • -ffile get list of filenames to check from file
  • -L if filename is a link, check the link
    references rather than the link itself
  • filename... name of file(s) to check

134
file
  • file is good when you have no idea what a file is
  • listing an executable or binary file to see what
    is in it can mess up your terminal display, and
    using an editor is more work

135
Change file MODe - chmod
  • Changes access permissions (mode) of a file
  • Syntax chmod -R mode filename
  • -R recursively descend through directory
    arguments, changing the mode for each file
  • mode new value for file access permissions
    mode, either octal or symbolic
  • filename filename(s) or directory(s) name to
    modify

136
Access Permissions
  • Each file and directory has a set of access
    permissions associated with it
  • You can see them by using the long form of ls
    (ls -l)

137
Access Permissions
  • Format is srwxrwxrwx
  • s is special, l for links, d for directories, t
    for sticky bit
  • r is read permission
  • w is write permission
  • x is execute permission
  • Three access levels exist, in order
  • User, Group, Other

138
Access Permissions
  • Only the owner (or superuser) can change the
    access permissions of a file
  • The execute bit must be set in order to cd into a
    directory
  • The shell variable umask sets the default access
    permissions when you create a new file

139
Octal Access Permissions
  • Octal notation consists of the numbers 0-7
  • In bit positions, the values of the bits are 4 2
    1
  • To determine the octal value, multiply the bit
    position value by its contents and add them up
  • 101 14 02 11 5
  • 110 14 12 01 6

140
Octal Access Permissions
  • To use octal access permissions, you do the same
    thing for each level of permissions
  • -rwxrw-r-- (00) (141211)
    (141201) (140201) 0764
  • Leading zeros can be ignored

141
Symbolic Access Permissions
  • Symbolic access permissions have the form who
    op permission op permission
  • Where who is
  • u user
  • g group
  • o other
  • a all
  • If who is omitted, all is assumed
  • op is , -, or for add, remove, or explicitly
    set
  • permission is r (read), w (write), or x (execute)

142
Symbolic Permissions Examples
  • chmod o-w file remove write permission from
    other
  • chmod gx file add execute permission to
    group
  • chmod uwr file explicitly make permissions
    for user read and write only (all other
    bits for group are reset when is used)

143
Symbolic Permissions Examples
  • chmod urwx grw o-w file
  • explicitly gives user all permissions, adds read
    and write to group and removes write from other
Write a Comment
User Comments (0)
About PowerShow.com