Sed - Usage

Usage

The following example shows a typical, and the most common, use of sed, where the -e option indicates that the sed expression follows:

sed -e 's/oldstuff/newstuff/g' inputFileName > outputFileName

In many versions, the -e is not required to precede the expression. The s stands for substitute. The g stands for global, which means that all matching occurrences in the line would be replaced. The regular expression (i.e. pattern) to be searched is placed after the first delimiting symbol (slash here) and the replacement follows the second symbol. Slash is the conventional symbol. Any other could be used to make syntax more readable if it does not occur in the pattern or replacement (see below), which is useful to avoid leaning toothpick syndrome.

Under Unix, sed is often used as a filter in a pipeline:

generate_data | sed -e 's/x/y/g'

That is, generate the data, and then make the small change of replacing x with y.

Several substitutions or other commands can be put together in a file called, for example, subst.sed and then be applied using the -f option to read the commands (such as s/x/y/g) from the file:

sed -f subst.sed inputFileName > outputFileName

Besides substitution, other forms of simple processing are possible. For example, the following uses the d command to delete lines that are either blank or only contain spaces:

sed -e '/^ *$/d' inputFileName

This example used some of the following regular expression metacharacters:

  • The caret (^) matches the beginning of the line.
  • The dollar sign ($) matches the end of the line.
  • The asterisk (*) matches zero or more occurrences of the previous character.

Complex sed constructs are possible, allowing it to serve as a simple, but highly specialised, programming language. Flow of control, for example, can be managed by the use of a label (a colon followed by a string) and the branch instruction b. An instruction b followed by a valid label name will move processing to the block following that label. If the label does not exist then the branch will end the script.

Read more about this topic:  Sed

Famous quotes containing the word usage:

    Pythagoras, Locke, Socrates—but pages
    Might be filled up, as vainly as before,
    With the sad usage of all sorts of sages,
    Who in his life-time, each was deemed a bore!
    The loftiest minds outrun their tardy ages.
    George Gordon Noel Byron (1788–1824)

    ...Often the accurate answer to a usage question begins, “It depends.” And what it depends on most often is where you are, who you are, who your listeners or readers are, and what your purpose in speaking or writing is.
    Kenneth G. Wilson (b. 1923)

    I am using it [the word ‘perceive’] here in such a way that to say of an object that it is perceived does not entail saying that it exists in any sense at all. And this is a perfectly correct and familiar usage of the word.
    —A.J. (Alfred Jules)