next up previous
Next: Shell Scripting Up: intro_Unix Previous: awk

sed

sed is a useful editor that can alter text that matches a particular pattern in a file or I/O stream. The basic syntax is sed script file, where the script contains a pattern to match and replace using ``regular expression'' rules (man regexp). The usage is best illustrated with examples. For more information, check the man pages or that awk and sed book by O'Reilly.

  1. Replace all occurences of ``foo'' with ``bar'' in a file:
        sed s/foo/bar/g file
    
    The g instructs sed to replace all occurences on a given line, rather than the first as is the default. Note that this invocation directs the output to the screen; use redirection to put it in a new file. Also, any character (except \) can be used in place of / to delimit the target and replacement, so long as the same character is used throughout. This can be useful when dealing with pathname substitutions.
  2. Replace all occurences of ``foo'' with ``bar'', but only in lines containing the keyword ``doh'':
        sed /doh/s/foo/bar/g file
    
  3. Same again, but this time replace the 4th occurence of ``foo'' and only on lines starting with ``doh'':
        sed /^doh/s/foo/bar/4 file
    
  4. Same again, but now ``doh'' must be at the end of the line:
        sed '/doh$/s/foo/bar/4' file
    
    Note the '' to hide the special meaning of $ to the shell.
  5. See the shell scripting section below for another example, namely using sed to rename files.


next up previous
Next: Shell Scripting Up: intro_Unix Previous: awk
Massimo Ricotti 2009-01-26