Sunday, August 7, 2011

Unix tool sed

sed (stream editor) is a Unix utility that parses text and implements a programming language which can apply transformations to such text. It reads input line by line, applying the operation which has been specified via the command line, and then outputs the line.

Sed is a powerful stream editor. Sed copies its input to its output, editing it in passing. Each portion of an input line matching a regular expression can be replaced with a fixed string or another portion of the input. Lines matching a regular expression can be deleted. GNU sed understands Unicode.

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

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

Samples

To delete a line containing a specific word from the file use:
sed '/yourword/d' yourfile
To delete only the word use:
sed 's/yourword//g' yourfile




No comments:

Post a Comment