

To update the content of the file with the sed command we need to pass an additional flag, the -i flag that edits files in place. …the file still contains the original message. Let’s check the content of the message.txt file using the cat command: ~]$ cat message.txt

~]$ sed 's/Athens/Rome/ s/Greece/Italy/' message.txt We can then use the same sed syntax we have seen in the previous section, this time we specify the sed command followed by the name of the file. ~]$ echo "Athens is the capital of Greece" > message.txt To create the file we redirect the output of the echo command to the new file. Now, instead of replacing strings in a message generated by the echo command, we will create a file that contains the same message. Using the Sed Command to Replace a String in a File ~]$ echo "Athens is the capital of Greece" | sed 's/Athens/Rome/ s/Greece/Italy/'Īs you can see we can use a single sed command and this time within the single quotes we specify two regular expressions separated by semicolon. In this way we wouldn’t have to use two sed commands. As we will see in the next section, we can also use a similar sed command to replace strings in a file.īefore moving to the next section I want to find out if it’s possible to use a single sed command to replace both strings. We replace the string Athens with the string Rome in the message printed by the echo command. So, in our case when we write: sed 's/Athens/Rome/' Between the second and the third slash you specify new_string that is the string we want to replace the original_string with. The letter s indicates the substitute command, it’s followed by three forward slashes.īetween the first and the second slash you can see original_string, that is the string we want to replace. Let’s look at the syntax of the two sed commands: sed 's/original_string/new_string/' They are both applied to the output of the echo command. I have used two pipes with two sed commands, one to replace the word Athens with Rome and the other one to replace Greece with Italy. ~]$ echo "Athens is the capital of Greece" | sed 's/Athens/Rome/' | sed 's/Greece/Italy/' Then using the pipe I will pass the output of the echo command to the sed command and replace the words Athens and Greece with Rome and Italy. With the echo command I will print the message “Athens is the capital of Greece” in the terminal: ~]$ echo "Athens is the capital of Greece"
#Bulk file string replacer how to
I will start with a simple example that shows how to use the sed command directly in the Linux command line. The sed command stands for stream editor, it’s one of the most powerful Unix tools to filter and transform text.
