Sed

From Gentoo Linux Wiki

Jump to: navigation, search



Contents

[edit] sed -- the Stream Editor

sed is a Linux/Unix command line programme which modifies strings. The command uses so-called regular expressions. It is very often used in shell scripts; e.g. many of the Gentoo portage programmes written in bash use sed. Sed works line-orientated, i.e. it reads the input line by line.

[edit] The s command

This is maybe the most common sed command. s stands for substitute.

[edit] Some examples

Example 1: Replacement (The echo "I hate linux" is just to generate some output; the operator "|", a so-called "pipe", redirects this to the sed command)

echo "I hate linux" | sed 's/hate/love/'

This means: In each line, replace the first occurrence of the string "hate" by "love".

The output would be

I love linux


Example 2: Global replacement

echo "yo yo yo " | sed 's/o/eah/g'

This means: In each line, replace all occurrences of the string "o" by "eah". Note the g at the end.

The output would be

yeah yeah yeah

Example 3: Regular expressions (The file mails.txt be a text file with a list of names, e-mail adresses and comments in the form John Smith <john.smith@example.com> -- My best friend)

cat mails.txt | sed -e 's/^.*<//' -e 's/>.*$//'

(The switch -e allows multiple expressions to be given.) The first expression means: Substitute everything from the beginning of each line (^) until the latest occurrence (*.)of the character < with nothing. The second expression means: Substitute everything from the first occurrence of the character > until the end of each line ($) with nothing.

The characters ^, *, . and $ are some members of the large family of regular expressions.

The output would be

john.smith@example.com
 .
 .
 .

[edit] TODO

The TODO list is moved to the talk page.

Retrieved from "http://gentoo-wiki.com/Sed"
Personal tools
In other languages