Text Substitution and Editing with Sed

Introduction to Text Substitution and Editing with Sed

Welcome! In this lesson, we will explore the powerful text processing tool sed in Bash. sed stands for "Stream Editor," and it is a versatile utility for parsing and transforming text in files or data streams. It reads text from a file or standard input, processes it according to specified commands, and outputs the modified text. It's commonly used for tasks like text substitution, deletion, and insertion in both files and data streams, making it an essential tool for automating text processing in scripts.

Understanding Text Substitution with Sed

Text substitution is one of the fundamental uses of sed. Suppose you want to replace all instances of the word "pattern" with "replacement" in a file. The syntax for this:

sed 's/pattern/replacement/' filename

This command searches for the first occurrence of the specified pattern and replaces it with replacement. The new text will then be output to the terminal. Let's replace the first occurrence of "Hi" with "Hello":

#!/bin/bash

echo "Hi World. Hi sed." > file.txt
echo "Output of sed command:"
sed 's/Hi/Hello/' file.txt

echo -e "\nContents of file.txt:"
cat file.txt

Output:

Output of sed command:
Hello World. Hi sed.

Contents of file.txt:
Hi World. Hi sed.

This command searches file.txt for the first occurrence of "Hi" and replaces it with "Hello" and outputs it to the terminal. "Hi sed." does not change to "Hello sed" because this command only searches for the first occurence of "Hi". Also notice that the contents of file.txt were not actually changed.

In-place Substitution

In many cases, you may want to make substitutions directly within the file. The -i option allows you to do this. You must ensure that the file has write permissions so sed can write to it. For this, you use the chmod +w command.

#!/bin/bash

echo "Hi World" > file.txt
chmod +w file.txt
sed -i 's/Hi/Hello/' file.txt

cat file.txt

Output

Hello World

Using -i, the contents of file.txt have been replaced. Notice that the actual sed command does not print anything to the terminal now.

Global Substitution

To replace all occurrences of a pattern in the file, add the g flag to the sed command.

#!/bin/bash

echo "Hi World. Hi sed." > file.txt
sed 's/Hi/Hello/g' file.txt

Output:

Hello World. Hello sed.

Now, all instances of Hi are replaced with Hello.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal