How to use sed command in Linux

sed, short for “stream editor”, allows you to filter and transform text. A stream editor is used to perform basic text transformations on an input stream (a file, or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed’s ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

How sed Works

sed maintains two data buffers: the active pattern space, and the auxiliary hold space. Both are initially empty.
sed operates by performing the following cycle on each line of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; each command can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed.

When the end of the script is reached, unless the -n option is in use, the contents of pattern space are printed out to the output stream, adding back the trailing newline if it was removed. Then the next cycle starts for the next input line.

Syntax

sed Options… [Script] [InputFile…]

Option Detail
-n, –quiet, –silent Suppress automatic printing of pattern space.
-e script, –expression=script Add the script script to the commands to be executed.
-f script-file, –file=script-file Add the contents of script-file to the commands to be executed.
–follow-symlinks Follow symlinks when processing in place.
-i[SUFFIX], –in-place[=SUFFIX] Edit files in place (this makes a backup with file extension SUFFIX, ifSUFFIX is supplied).
-l N, –line-length=N Specify the desired line-wrap length, N, for the “l” command.
–POSIX Disable all GNU extensions.
-r, –regexp-extended Use extended regular expressions in the script.
-s, –separate Consider files as separate rather than as a single continuous long stream.
-u, –unbuffered Load minimal amounts of data from the input files and flush the outputbuffers more often.

Example

#Replacing word in a file and save the output in same file.
       sed -i ‘s/blogger/blog/g’ test_sed.txt

sed command

Leave a Reply

Your email address will not be published. Required fields are marked *