Security

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 :

#sed 'ADDRESSs/REGEXP/REPLACEMENT/FLAGS' filename
#sed 'PATTERNs/REGEXP/REPLACEMENT/FLAGS' filename
  • 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
echo "Linux Sysadmin, Linux Scripting etc" | sed 's/Linux/Linux-Unix'

output > Linux-Unix Sysadmin, Linux Scripting etc

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

echo "Linux Sysadmin, Linux Scripting etc" | sed 's/Linux/Linux-Unix/g'

Output > Linux-Unix Sysadmin, Linux-Unix Scripting etc

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

echo "Linux Sysadmin, Linux Scripting etc" | sed 's/Linux/Linux-Unix/2'

Output > Linux Sysadmin, Linux-unix Scripting etc

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

echo "Linux Sysadmin, Linux Scripting etc" | sed 's/Linux/Linux-Unix/gw output'

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

echo "Linux Sysadmin, Linux Scripting etc" | sed '/\etc/s/Sys.*//g'

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

 

 

 

Leave a Reply

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