开发者

sed variable replacement does not seem to work

开发者 https://www.devze.com 2023-02-03 13:27 出处:网络
I set up a variable in the shell: -bash-3.00$ echo $source_repl source ../setup_simple.tcl I then tried to replace a line in a file that started with the string \"package require IxLoad\" with the

I set up a variable in the shell:

-bash-3.00$ echo $source_repl
source ../setup_simple.tcl

I then tried to replace a line in a file that started with the string "package require IxLoad" with the variable string (noting that double quotes are the way to get sed to use variable substitution). First I tried with direct substitution (no escapin开发者_如何学编程g the $ in the variable):

-bash-3.00$ sed -e "s/package require IxLoad.*/$source_repl/g" smtp_tput191Mb.tcl > tmpwatch.tcl
sed: -e expression #1, char 38: unknown option to `s'
-bash-3.00$

So I thought that escaping the $ would solve the problem but as you can see the line is then replaces by the literal string "$source_repl" rather than the variable stored there:

-bash-3.00$ sed -e "s/package require IxLoad.*/\$source_repl/g" smtp_tput191Mb.tcl > tmpwatch.tcl
-bash-3.00$ diff smtp_tput191Mb.tcl tmpwatch.tcl
11c11
< package require IxLoad
---
> $source_repl
-bash-3.00$ 

I looked up many sites on how to do variable substitution in sed and they all seem to indicate that the above should work. What am I missing? Is there something in the actual variable that's causing this?

A


There is a / in your variable. Use @ as pattern separator and this will go.

sed -e "s@package require IxLoad.*@$source_repl@g" smtp_tput191Mb.tcl > tmpwatch.tcl


I don't know how to work this issue around in general (changing the separators is easy, but you never know what can be in the variable), but if you can use perl instead of sed, you could load the environment variable form inside perl to avoid the escaping issue:

perl -pe 's/package require IxLoad.*/$ENV{source_repl}/g' smtp_tput191Mb.tcl > tmpwatch.tcl


Sorry for wasting your time folks. I found the problem. I needed to escape the dots and slashes in the actual variable in order to replace it with the sed statement:

-bash-3.00$ echo $source_repl
source \.\.\/setup_simple\.tcl
-bash-3.00$ sed -e "s/package require IxLoad.*/$source_repl/g" smtp_tput191Mb.tcl > tmpwatch.tcl
-bash-3.00$ diff smtp_tput191Mb.tcl tmpwatch.tcl                                          11c11
< package require IxLoad
---
> source ../setup_simple.tcl
-bash-3.00$

Thanks

0

精彩评论

暂无评论...
验证码 换一张
取 消