Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed not working inside bash script

Tags:

I believe this may be a simple question, but I've looked everywhere and tried some workarounds, but I still haven't solved the problem.

Problem description: I have to replace a character inside a file and I can do it easily using the command line:

sed -e 's/pattern1/pattern2/g' full_path_to_file/file 

But when I use the same line inside a bash script I can't seem to be able to replace it, and I don't get an error message, just the file contents without the substitution.

#!/bin/sh  VAR1="patter1" VAR2="patter2"  VAR3="full_path_to_file"  sed -e 's/${VAR1}/${VAR2}/g' ${VAR3} 

Any help would be appreciated.

Thank you very much for your time.

like image 645
Isabelle Avatar asked Jun 10 '10 15:06

Isabelle


People also ask

Can you use sed in bash script?

Bash allows you to perform pattern replacement using variable expansion like (${var/pattern/replacement}). And so, does sed like this (sed -e 's/pattern/replacement/'). However, there is more to sed than replacing patterns in text files.

Why is sed not working?

Because you are using PCRE (Perl Compatible Regular Expressions) syntax and sed doesn't understand that, it uses Basic Regular Expressions (BRE) by default. It knows neither \s nor \d .

What is sed in bash?

sed is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement. The s,%,$,g part of the command line is the sed command to execute. The s stands for substitute, the , characters are delimiters (other characters can be used; / , : and @ are popular).


2 Answers

Try

sed -e "s/${VAR1}/${VAR2}/g" ${VAR3} 

Bash reference says:

The characters ‘$’ and ‘`’ retain their special meaning within double quotes

Thus it will be able to resolve your variables

like image 185
Dmitry Yudakov Avatar answered Oct 02 '22 19:10

Dmitry Yudakov


I use a script like yours... and mine works as well!

#!/bin/sh  var1='pattern1' var2='pattern2'  sed -i "s&$var1&$var2&g" *.html 

See that, mine use "-i"... and the seperator character "&" I use is different as yours. The separator character "&" can be used any other character that DOES NOT HAVE AT PATTERN.

You can use:

sed -i "s#$var1#$var2#g" *.html  sed -i "s@$var1@$var2@g" *.html 

...

If my pattern is: "[email protected]" of course you must use a seperator different like "#", "%"... ok?

like image 23
Carlos Eduardo Baldocchi Avatar answered Oct 02 '22 20:10

Carlos Eduardo Baldocchi