Linux Command - sed

sed - stream editor for filtering and transforming text. The most well-known use case for sed is substituting text.

Syntax

1
sed [OPTIONS] commands [input-file]

Options

Option Description
-i edit files in place
-r, –regexp-extended use extended regular expressions in the script.
-n, --quiet, --silent suppress automatic printing of pattern space

s command

The s command is the most important in sed. s command syntax is

1
/regexp/replacement/flags

The most common flags are

  • g - apply the replacement to all matches, not just the first.
  • I or i - case insensitive replace

Examples

String Substitution

use s command to substitute string.

1
2
3
input=ABCDEFGHI
result=$( echo $input | sed 's|DEF|---|') # replace 'DEF' with '---'
echo $result

Note: sed 's|DEF|---|g' is the same as sed 's/DEF/---/g', ‘g’ flag is for global.

String Substitution for a file

To replace abc with ABC in file1

1
sed 's/abc/ABC/g' file1

to save as new file

1
sed 's/abc/ABC/g' file1 > file2

To do in place replace abc with def in inputfile

1
sed -i 's/abc/def/g' inputfile

Handling Single quote

Substitube with single quote. To replace "uid" with 'uid' in inputfile

1
sed "s|\"uid\"|'uid'|g" inputfile

Example to Replace UUID

To replace uuid in uuid.json file

1
2
3
{
"uid": "9EF7229B-444E-4062-B843-97527E25660C"
}

To replace UUID in this file. We need to use -r option to use extended regular expressions in the script. The complete script is:

1
2
#!/bin/bash
sed -r "s|\"uid\": \".{36}\"|\"uid\": \"$(uuidgen)\"|g" uuid.json

Reference