Linux Sed Command With Examples

Hi All,

Today we are going to see about “SED” command with examples.

What is SED ?

sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file, or input from a pipeline)

We can do more text operations using SED command. But in this article we mainly focus on SED substitution operations.

SYNTAX for Sed Substitution :

  • s is substitute command
  • / is a delimiter
  • REGEXP is regular expression to match
  • REPLACEMENT is a value to replace

FLAGS can be any of the following

  • g Replace all the instance of REGEXP with REPLACEMENT
  • n Could be any number,replace nth instance of the REGEXP with REPLACEMENT.
  • p If substitution was made, then prints the new pattern space.
  • i match REGEXP in a case-insensitive manner.
  • w file If substitution was made, write out the result to the given file.
  • We can use different delimiters ( one of @ % ; : ) instead of /

Let’s see some interesting examples.

  1. Substitute Word “Linux” to “Linux-Unix” Using sed

In the example below, in the output line “Linux-Unix Sysadmin, Linux Scripting etc” only first Linux is replaced by Linux-Unix. If no flags are specified the first match of line is replaced.

2. Substitute all Appearances of a Word Using sed s

The below sed command replaces all occurrences of Linux to Linux-Unix using global substitution flag “g”.

3. Substitute Only 2nd Occurrence of a Word Using sed

In the example below, in the output line “ Linux Sysadmin, Linux-Unix Scripting etc.” only 2nd occurance of Linux is replaced by Linux-Unix.

4. Write Changes to a File and Print the Changes Using sed

The example below has substitution with two flags. It substitutes all the occurance of Linux to Linux-Unix and prints the substituted output as well as written the same to the given the file.

5. Substitute Only When the Line Matches with the Pattern Using sed

In this example, if the line matches with the pattern “etc“, then it replaces all the characters from “Sys” with the empty.





View all posts by

Leave a Reply

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