Sed

sed is a stream editor. This sounds scary in the WYSIWYG GUI world to have an editor that does not have a menu or mouse support. see https://devmanual.gentoo.org/tools-reference/sed/index.html or http://www.grymoire.com/Unix/Sed.html.

  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

With sed files can be edited automatically line by line using a single line to call sed. For somebody using sed once a while its syntax and regular expressions is an obstacle, but ask ChatGPT what you want to do as:

Remove commenting lines starting with the # character and the result will be:

sed -i '/^#/d' <filename.txt>

or remove commenting lines with # but do not remove them with ##

sed -i '/^#[^#]/d' <filename.txt>

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