Ultimate Sed Tutorial With Examples

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/ultimate-sed-tutorial-with-examples/
PINTEREST
PINTEREST
INSTAGRAM

Sed is stream editor. Sed is used to transform text according to different needs. Sed have a scripting language set too. Sed scripts can be run against files as we see our examples below.  Now we should start example because this tutorial is one of the most long tutorial in this site.

Syntax

Sed have following syntax where input files are provided as the last option.

Help

More help about sed can be get with man page like below.

Sed Help

Sed Help

Or by just issuing the sed command in the bash without a parameter will print main help information.

Sed Help

Sed Help

Example Text

During sed tutorial we will need a sample text file where we use commands and options in this text file. We name this text file as mytext.txt like below.

Print Matched Lines

We want to print the lines those matched given string. In this example we will print the lines with poftut by using p command.

Print Specified Line Numbers

Sed provides support to print only given lines according to their numbers. We will print line 3 with p command in this example.

Print Specified Line Range According Numbers

In previous example we have only printed single line. We can also print multiple lines by providing the start and end numbers of lines. In this example we will print lines between 2 and 4 .

LEARN MORE  Awk Text Split and Delimit Examples

Print Specified Line Range According Numbers

Print Specified Line Range According Numbers

Replace Text

One of the most used feature of the sed is replacing text. We will use s/foo/bar/g command. s/ is used to search foo/ and g is used to replace /var with matches of search. Or simply this will replace foo with bar .

In this example we will replace poftut with POFTUT

Replace Text

Replace Text

Delete Matched Word

In text we can delete matched words we have given. This is similar to substitute where we do not provide replacement word. In this example we will remove the word poftut .

Delete Matched Word

Delete Matched Word

Delete Matched Lines

Similar to the previous example we can delete a word matched line as a whole. In this example we will delete lines where those contains poftut with the d operation

Delete Matched Lines

Delete Matched Lines

Put New Line After Each Line

We may need to create new line after each line to the end of the file. We can use G for this operation.

Put New Line After Each Line

Put New Line After Each Line

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/ultimate-sed-tutorial-with-examples/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)