Common Commands (sed, a stream editor)
Next: Other Commands, Previous: The "s" Command, Up: sed scripts [Contents][Index]
3.4 Often-Used Commands
If you use sed at all, you will quite likely want to know these commands.
#[No addresses allowed.]
The
#character begins a comment; the comment continues until the next newline.If you are concerned about portability, be aware that some implementations of
sed(which are not POSIX conforming) may only support a single one-line comment, and then only when the very first character of the script is a#.Warning: if the first two characters of the
sedscript are#n, then the-n(no-autoprint) option is forced. If you want to put a comment in the first line of your script and that comment begins with the letter ‘n’ and you do not want this behavior, then be sure to either use a capital ‘N’, or place at least one space before the ‘n’.q [exit-code]Exit
sedwithout processing any more commands or input.Example: stop after printing the second line:
$ seq 3 | sed 2q 1 2
This command accepts only one address. Note that the current pattern space is printed if auto-print is not disabled with the
-noptions. The ability to return an exit code from thesedscript is a GNUsedextension.See also the GNU
sedextensionQcommand which quits silently without printing the current pattern space.dDelete the pattern space; immediately start next cycle.
Example: delete the second input line:
$ seq 3 | sed 2d 1 3
pPrint out the pattern space (to the standard output). This command is usually only used in conjunction with the
-ncommand-line option.Example: print only the second input line:
$ seq 3 | sed -n 2p 2
nIf auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then
sedexits without processing any more commands.This command is useful to skip lines (e.g. process every Nth line).
Example: perform substitution on every 3rd line (i.e. two
ncommands skip two lines):$ seq 6 | sed 'n;n;s/./x/' 1 2 x 4 5 x
GNU
sedprovides an extension address syntax offirst~stepto achieve the same result:$ seq 6 | sed '0~3s/./x/' 1 2 x 4 5 x
{ commands }A group of commands may be enclosed between
{and}characters. This is particularly useful when you want a group of commands to be triggered by a single address (or address-range) match.Example: perform substitution then print the second input line:
$ seq 3 | sed -n '2{s/2/X/ ; p}' X
Next: Other Commands, Previous: The "s" Command, Up: sed scripts [Contents][Index]