Welcome back! In this post we are discussing the sed utility, more precisely, the inline function.
Sed stands for Stream EDitor. Sed can be used to manipulate text files from standard input or inline. In this article we will examine the inline function of sed.
Let’s take a look at the following command:
echo “This is a test for sed” | sed ‘s/test/goot test/’
The output like you should see is: This is a good test for sed. The command above echoed This is a test for sed piped STDOUT to sed STDIN and sed command searched for the string names test and replaced it with good test and put the sentence in STDOUT.
Go a head and experiment with the sed utility to better understand it.
Now, let’s dive into the inline function of sed. Let’s say that you have a file called customers.txt and you need to change all the first names of the customers named Mike to Michael. Now there are many ways to accomplish this, with sed, the advantage is that you can script it.
The sed command to change all the instances of Mike into Michael is:
sed -i ‘s/Mike/Michael/g’ customers.txt
The command above will change all the strings Mike into Michael for the file customers.txt; this what inline in sed means, make the changes to the file instead of just putting them in STDOUT.
Now, you could accomplish the same by editing the file with a text editor and do a global search and replace. So, no real advantages here. Now let’s assume you have 1000 text customer files, and you have to change the name Mike into Michael. This is where sed shines. The command to perform the task is:
sed -i ‘s/Mike/Michael/g’ *.txt
As you can see from the command above, the inline sed can be used on many files at once. This is really where the advantage of using inline sed should be obvious.
There are many more use cases for using sed. This post is meant as an introduction only. Experiment with sed to understand its potential.
This article is meant to be simple and concise.