sed command to replace string

Sed Command to Replace String in File

Sed is a powerful Linux command to work with string and texts in Linux. It allows you to easily find, modify, add, delete strings from text files. Sometimes you may need to replace a string in file. You can easily do this using sed command. In this article, we will learn sed command to replace string in file.


Sed Command to Replace String in File

Sed is a powerful function with the following syntax for string replacement.

sed -i 's/old-text/new-text/g' input.txt

In the above command, the s option is for string substitution. -i option is to update the input file. Also /g means replace all occurrences.

Here are some example using sed. Let us say you have the following file data.txt

$ cat data.txt
foo is good
foo is bad

Here is the sed command to replace the first occurrence of foo with bar in data.txt

$ sed -i '/foo/bar' data.txt
$ cat data.txt
bar is good
foo is bad


Now will look at some use cases.

Replace string in multiple lines

Here is the sed command to replace all instances of foo with bar. It is important to add /g after new text, for global substitution.

$ sed -i /foo/bar/g data.txt


Replace string in multiple files

Sed command allows you to work with only one file at a time. If you want to replace the same string in multiple files, you will need to use sed command with find command or xargs command. Here is the above sed command to replace foo with bar in files data1.txt data2.txt data3.txt.

$ find . -type f -name 'data*txt' -exec sed -i 's/foo/bar/g' {} \;

In the above command, find will search for all files starting with data and ending with txt and execute sed command to on each of them to replace foo with bar.

Alternatively, you can also use xargs command.

$ find . -type f -name 'data*txt' | xargs sed -i 's/foo/bar/g'

In the above command, find will locate all files starting with data and ending with txt, and pass it to xargs command which generates individual sed commands for each file.



Replace special characters

Please note, if your old or new string contains special characters like backslash, asterisk, single quote, etc., then you need to escape it with another backslash. Here is the sed command to replace tom’s with fred’s.

$ sed -i '/tom\'s/fred\'s/g' input.txt

If there are multiple special characters one after the other you need to escape each character separately. Here is the sed command to replace *** with aaa.

$ sed -i /\*\*\*/aaa/g' input.txt

In this article, we have learnt how to use sed command to replace string in Linux. You can use these commands on almost every Linux system since it is available on many distributions.

Also read:

What is __name__ in Python
How to Find Non-ASCII Characters in MySQL
How to Use Reserved Word in MySQL
How to Show Banned IP Address in Fail2ban
How to Unban IP Address with Fail2ban

Leave a Reply

Your email address will not be published. Required fields are marked *