sed

From NetBSD Wiki

Jump to: navigation, search

The sed(1) (stream editor) utility can be used to edit streams of data on the fly.

Contents

Examples

Replacing:

$ echo "cows go baa" | sed 's/cows/sheep/'
sheep go baa

The word "cows" has been replaced with "sheep".

$ echo "GNU: GNU's Not Unix" | sed 's/GNU/Linux/g'
Linux: Linux's Not Unix

By default, sed will only replace the first occurence on each line. By specifying the "g" flag, all occurences are replaced.

Gotchas

GNU sed (textproc/gsed) also accepts regexes where an address is expected. Ours does not, which means some sed scripts you may encounter might not appear to work.

Tutorial

This is a basic sed tutorial

Printing

-- input file --

$ cat file
Line one, this is line 1.
Line two, this is line 2.
Line three, this is line 3

-- input file --


Print the first line of the input file.

$ sed -n '1p' file
Line one, this is line 1.

Print the last line of the input file.

$ sed -n '$p' file
Line three, this is line 3

Print lines 2 through three of the input file.

$ sed -n '2,3p' file
Line two, this is line 2.
Line three, this is line 3

Print from line 2 through the end of the file.

$ sed -n '2,$p' file
Line two, this is line 2.
Line three, this is line 3

Print all lines except line 2 of the input file.

$ sed -n '2!p' file
Line one, this is line 1.
Line three, this is line 3

Print those lines that contain the characters 'three'.

$ sed -n '/three/p' file
Line three, this is line 3

Print from the line that contains the characters 'two' to the character '3'. This is of course if 'two' and '3' are found in the file. If 'two' was found but not '3' sed would print everything from 'two' to the end of the file, if 'two' was not found sed would print nothing.

$ sed -n '/two/,/3/p' file
Line two, this is line 2.
Line three, this is line 3

Print from line 1 down to the characters 'two'.

$ sed -n '1,/two/p' file
Line one, this is line 1.
Line two, this is line 2.

to be continued ...

See also

Retrieved from "http://wiki.netbsd.se/sed"
Personal tools