Have you ever tried to change text in a file via the Linux terminal? I know you think this is only possible with text editors like VIM or nano. In reality, it's possible to change text without even having to open a file, in which case you can use the SED Command.
In this article, you will see how to achieve that.
What is Sed Command
SED stands for stream editor. It reads the given file, modifying the input as specified by a list of sed commands. By default, the input is written to the screen, but you can force update the file.
How to Find and Replace Text Within a File using Sed Command
Take this code snippet below
$ sed -i 's/old-text/new-text/g' randomFile.txt
The Stream EDitor above performs all these operations:
- It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named randomFile.txt
- The
s
is the substitute command of sed for find and replace. - The
g
is for globally, means it will replace all the matching text from the left - The
-i
tells to update the file - The
/
is the default delimiter, but it can be another character other than backslash (\) or newline (\n)
Once you have run the command above, you can verify that the file has been updated
$ cat randomFile.txt
SED Command problems with the default delimiter
We have seen earlier that /
character, is the default delimiter, but sometimes we want to change text that has this character in his string. Take this simple use case.
$ cat htaccess.txt
http:// is no longer used.
Please consider using https:// instead
Now we would like to find the word http://
and replace with https://
$ sed 's/http:///https:///g' htaccess.txt
You will get an error like this
sed: 1: "s/http:///https:// ...": bad flag in substitute command: '/'
Our syntax is correct, but the /
delimiter character is also part of http://
and https://
in the above example. The Sed command allows you to change the delimiter / to something else.
So we are going to use @
to bypass this error:
$ sed 's@http://@https://@g' htaccess.txt
We will then get this sample output
https:// is no longer used.
Please consider using https:// instead
That's it! I hope this tutorial helped.
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts or opinions below in the comments section.
You can have more of my content by following me on LinkedIn • GitHub or Medium