1. Technology
Linux / Unix Command: sed
Command Library

NAME

sed stands for "stream editor".

SYNOPSIS

% sed [-an] command [file ...]
% sed [-an] [-e command] [-f command_file] [file ...]

DESCRIPTION

sed can be used to filter text files. The pattern to match is typically included between a pair of slashes // and quoted.
For EXAMPLE, to print lines containing the string "1024", you may use:

cat filename | sed -n '/1024/p'

Here, sed filters the output from the cat command. The option "-n" tells sed to block all the incoming lines but those explicitly matching the expression. The sed action on a match is "p"= print.
Here is another EXAMPLE, this time for deleting selected lines:

cat filename | sed '/.*o$/d' > new_file

In this EXAMPLE, lines ending with an "o" will be deleted. It uses a regular expression for matching any string followed by an "o" and the end of the line. The output (i.e., all lines but those ending with "o") is directed to new_file.

To search and replace, use the sed 's' action, which comes in front of two expressions:

cat filename | sed 's/string_old/string_new/' > newfile

A shorter form for the last command is:

sed 's/string_old/string_new/' filename > newfile

To insert text from a text file (text_added.txt) into an html file, you may use a script containing:

sed '/placeholder_text_in_html_file/r text_added.txt'
index_master_file.html > index.html

OPTIONS

-a
The files listed as parameters for the ``w'' functions are creat-
ed (or truncated) before any processing begins, by default. The
-a option causes sed to delay opening each file until a command
containing the related ``w'' function is applied to a line of in-
put.

-e command
Append the editing commands specified by the command argument to
the list of commands.

-f command_file
Append the editing commands found in the file command_file to the
list of commands. The editing commands should each be listed on
a separate line.

-n
By default, each line of input is echoed to the standard output
after all of the commands have been applied to it. The -n option
suppresses this behavior.

EXAMPLE

See above, in the DESCRIPTION section.

Important: Use the man command (% man) to see how a command is used on your particular computer.

>> Linux Command Library Index

>> Also see Shell Command Library

You can opt-out at any time. Please refer to our privacy policy for contact information.

Discuss in my forum

©2014 About.com. All rights reserved.