Individual Home Directory Unix/Linux App

Submitted by: Submitted by

Views: 31

Words: 627

Pages: 3

Category: Science and Technology

Date Submitted: 02/09/2015 04:20 AM

Report This Essay

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...