Summary of sed

I sometimes visit the basic commands to refresh my memory. You work on so many different things in your real work, so it’s not possible to remember all the details of each command. I’ll go over sed in this blog article.

The description of sed in its man page says the following.

The sed utility reads the specified files, or the standard input if no files are specified, modifying the input as specified by a list of commands. The input is then written to the standard output.

The syntax looks like this.

sed [option] [script] [target file]

There are so many options and usages but I will just summarize the ones that are used often.

Sample Text File

Here is the content of sample.txt

Hello
Heeeeello
Helloooooo
foobar1
foobar2
foobar3

Print Certain Lines to Standard Output

sed -n 1,3p sample.txt 

The command above prints from the first line to the 3rd line in sample.txt file. The output looks like the following.

Hello
Heeeeello
Helloooooo

It is possible to list the lines that match regular expression.

sed -n /^He.*llo/p sample.txt

The result looks like the following.

Hello
Heeeeello
Helloooooo

Remove Lines

sed 1,3d sample.txt

The command above removes the lines from 1 to 3 and outputs the rest of the text to the standard output. Please note that the command will not remove those lines from the file itself but it just outputs the result in the standard output. The sample output shows like the following.

foobar1
foobar2
foobar3

It’s also possible to remove lines using regular expression. Please see the example below.

sed /^Hello/d sample.txt

The command above removes lines that start with “Hello”. The output will show like this.

Heeeeello
foobar1
foobar2
foobar3

Replace Texts

sed can replace certain text with something else based on regular expression like the following.

sed s/He.*llo/boo/g sample.txt

The result looks like the following.

boo
boo
booooooo
foobar1
foobar2
foobar3

Author: admin

A software engineer in greater Seattle area

Leave a Reply

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