Sed

sed is a stream editor. This sounds scary in the WYSIWYG GUI world see https://devmanual.gentoo.org/tools-reference/sed/index.html or http://www.grymoire.com/Unix/Sed.html. There are reasons why bother with something that looks rather nostalgic and has not even mouse support and a menu bar:

  1. sed takes all of its inputs from stdin a pipe can be used to feed it. So if called it freezes in the console. Therefore call it best with a file so an EOF comes.

  2. sed can be called from scripts

A good introduction is http://www.grymoire.com/Unix/Sed.html

sed is called as:

sed <options> '<command>' <inputfile>

The single quotes are not necessary but strongly recommended so that the shell never tries to expand it.

sed works as follows:

  1. It takes the input file and the commands from stdin

  2. It reads a line and stores it into its internal pattern buffer

  3. It executes the command to the internal pattern buffer

  4. It puts the result inside the internal pattern buffer to stdout (Note: The input file will not be modified except the -i option is added).

  5. It goes to step 2 until the end of the file has been reached

Filtering certain lines

Of course there are options to limit the commands just to certain lines.

A single line:

sed <options> '<linenumber><command>' <inputfile>

A range of lines:

sed <options> '<first line>,<last line><command>' < inputfile>

A regular expression:

sed '<regular expression><command>' <inputfile>

All lines from a first regular expression to a second regular expression.

sed '<first regular expression>,<second regular expression><command>' < inputfile>

Sed Commands

d delete

p print

s/<find>/<replace>/g find a string and replace it globally

sed 's/\t/ /g' <inputfile> > <output file> replaces tab characters with a blank

sed -i 's/<xxx>/<yyyy>/g' <file> replaces xxx with yyyy in a file

sed -i 's/<xxx>//g' <file> deletes xxx in a file

Sed Options

-n usually all lines if not deleted will be printed. -n does just print the lines that match the -p command.


Linurs startpage