Ultimate Sed Tutorial With Examples – POFTUT

Ultimate Sed Tutorial With Examples

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

Syntax

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

Help

More help about sed can get with pageman like below.

Sed Help

Sed Help

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

Sed Help

Sed Help

Example Text

During the tutorialsed, we will need an example text file where we use commands and options in this text file. We name this text file as likemytext.txt below.

Print Matched Lines

We want to print the lines those matched given string. In this example, we will print the lines with bypoftut using commandp.

Print Specified Line Numbers

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

Print Specified Line Range According Numbers

In the previous example, we have only printed a 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  Vim Undo and Redo Operations

Print Specified Line Range According Numbers

Print Specified Line Range According Numbers

Replace Text

One of the most used features 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 the 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 a 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

3 Responses

  1. vinci says:

    Why the hell would you call this ‘ultimate sed tutorial’ when you barely explain the basics?

  1. 08/01/2018

    […] Ultimate Sed Tutorial With Examples […]

Leave a Reply

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

Enjoy this blog? Please spread the word :)