Home » Unix command and scripts » How to use sed replace string in file

How to use sed replace string in file

We often need to replace strings in a file or multiple files in a Unix system. This can be done easily using the sed command. we can easily replace the strings in multiples in a very short span of time

sed replace a string in a file

We can use the below command

sed  's/<string 1>/<string 2>'  < file name> 

The above will not touch the file, it will provide the output with replacement strings. Also, It would do the first replacement on each line

Example
$cat test.txt
aaaaa

bbbb

CCCCC
ddddd
$sed  's/aaaaa/mmm' test.txt
mmm

bbbb

CCCCC
ddddd

Now if we want to replace the string from the file itself

sed  -i  's/aaaaa/mmm'  < file name> 

The above command will change the file itself

Example 
 $cat test.txt 
aaaaa 

bbbb 

CCCCC 
ddddd 
$sed -i  's/aaaaa/mmm' test.txt
$cat test.txt
mmm

bbbb

CCCCC
ddddd

We can change multiple files also using the same command.

sed  -i  's/aaaaa/mmm'  *txt

If it is required to do the second replacement on each line, the command would be

sed  's/<string 1>/<string 2>/2'  < file name> 

If it is required to do all the replacements on each line, the command would be

sed  's/<string 1>/<string 2>/g'  < file name> 

How to backup the files before the replacement

This can be done using the command

sed -i.bak 's/<string 1>/<string 2>'  *txt
  • This will make a backup of all the files with the “.bak” extension before changing it
  • Remember there is no space after i
See also  How to create ,List and unzip Tar.gz file in Linux

sed replace a string in a file when another string is not present

We can be using below command

sed '/<string 3>/!s/<string 1>/<string 2>/g'

Here string 3 is the string that should not be present when doing a replacement

sed '/watch/!s/bat/cat/g'

sed replace string with variable

We can use variables in the above command also, but you need to put “” instead of single quotes

for i in ls *html
do
x=cat
sed -i "s/$x/bat/g" $i
done

If you have / in the variable, use pipe in sed

for i in ls *html 
do
x=cat/jet
sed -i "s|$x|bat|g" $i
done

Hope you like this article

Related Articles
sed command in unix
sed to remove comments

Leave a Comment

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

Scroll to Top