简体   繁体   中英

How to do in place replacement into another file in unix shell scripting

I have two files test01 and test02 as below

Test01 file:

RX_HOME=/app/rx/rx01/mxIII
SCR_HOME=/app/scr/scr01/mxIII
JAVA_HOME=/opt/java/jdk1.7.0_51
SYBASE_HOME=/opt/sybase
ORACLE_HOME=/opt/oracle/11202
MX_HOST=ukloldk008
DB_HOST=ukloldk0004

Test02 file:

<MX_HOME>;
SCR_HOME;
;JAVA_HOME;
"SYBASE_HOME"
{ORACLE_HOME}
[MX_HOST]
\DB\DB_HOST\HOST\

I want a unix script which will read the test01 file and replace with the value of the variables from test01 into test02 wherever the name of the variable appears inside test02 file. My result should be like below in test02 file

</app/rx/rx01/mxIII>;
/app/px/px01/mxIII;
;/opt/java/jdk1.7.0_51;
"/opt/sybase"
{/opt/oracle/11202}
[ukloldk008]
\DB\ukloldk0004\HOST\

Could you kindly help on it

As I have wrote a script but not getting required result and when I am using sed getting (sed: illegal option -- i) error

#! /bin/bash
while IFS='=' read f1 f2
do
perl -pi -e 's/$f1/$f2/g' test02
done< test01

When you put the variables $f1 and $f2 into single quotes, the shell doesn't expand them. They get interpreted as Perl variables, but they're empty. Switch to double quotes.

Also, as the variables might contain slash, you can't use it as the separator in the substitution. Switch to a different character:

while IFS== read f1 f2 ; do
    perl -i~ -pe "s=$f1=$f2=g" test02
done < test01

If the files are large, it might be faster to do the whole work in Perl:

perl -e 'while (not eof) {
             chomp(($k, $v) = split /=/, <>);
             $h{$k} = $v;
         }
         $re = join "|", keys %h;
         while (<>) {
             s/($re)/$h{$1}/g;
         print;
     }' test01 test02 > test02.new

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM