How to Replace a Variable in a File Using SED
by Suparna Ganguly

Want to know the tricks of replacing a variable in a file using the SED command?

This article will give you an overview of replacing a variable value in a file using SED. Before replacing a variable in a file using SED, you need to understand what SED is, the syntax of SED, and how SED works.

I’ll also show how to perform delete operations using SED. This will come after the variable value replacement part. If you’re looking for that, you can directly jump onto that, and skip the rest.

So, let’s begin the guide.

 

What is SED?

So, what is  SED?

SED command in Linux stands for Stream Editor. It performs searching, insertion, find and replace, deletion. In the Linux world, SED is mainly popular for its find and replace functionality.

With the help of SED, coders can edit files without even opening them.

In a nutshell,

  • SED is a text stream editor. It can be used to do find and replace, insertion, and delete operations in Linux.

  • You can modify the files as per your requirements without having to open them.

  • SED is also capable of performing complex pattern matching.

 

Syntax of SED

Here we’ll see the syntax of SED used in a simple string replacement. This will help understand the command better.

So the syntax is:

sed -i 's/old-string/new-string/g' file_name

 

How SED Works

In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well.

Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.

Here’s a quick example to clear the concept.

Suppose, we have a random text “Welcome to Linux Channel” in a text file called “file.txt”.

Now, we want to replace “Channel” with “Family”. How can we do that?

First, write the below-given command in the terminal to create the file.

cat file.txt

Press enter, then type:

Welcome to Linux Channel

Let’s alter “Channel” with “Family” now. So, go to the next line, and type:

sed -i 's/Channel/Family/g' file.txt

After running the command, to view the file again, type:

cat file.txt

You’ll see “Channel” has been replaced with “Family”. In this way, you can replace a string using the SED command. Let’s learn how to replace a variable using SED, now.

Similar Posts