Need to replace a file contents

aixsed

I am stuck in a situation. I have a file script.txt with contents

$cat script.txt

SET TABLESPACE CONTAINERS FOR 3
-- IGNORE ROLLFORWARD CONTAINER OPERATIONS
USING (
FILE '/db2data2/dbs/rahtest/rahtest1.lrg'  5120
);


SET TABLESPACE CONTAINERS FOR 4
-- IGNORE ROLLFORWARD CONTAINER OPERATIONS
USING (
  FILE   '/db2data2/dbs/rahtest/rahtest2.lrg'  5120
);

My requirement is the filesystems in the lines

FILE '/db2data2/dbs/rahtest/rahtest1.lrg' 5120
FILE   '/db2data1/dbs/rahtest/rahtest2.lrg'  5120

I need to replace

/db2data2/dbs/rahtest/rahtest1.lrg

and

/db2data2/dbs/rahtest/rahtest2.lrg

with other filesystems; say

/db2data3/dbs/rahtest/rahtest1.lrg

and

/db2data3/dbs/rahtest/rahtest2.lrg

respectively.

Other parts should be the same. My output be such that the lines be now–

FILE '/db2data3/dbs/rahtest/rahtest1.lrg'  5120
FILE '/db2data3/dbs/rahtest/rahtest2.lrg'  5120

It should reflect in my file. I don't know the position of the lines in the line. I tried with sed. I tried to put the lines into variables say var1 and var2

var1=`echo /db2data2/dbs/rahtest/rahtest1.lrg'
var2=`echo /db2data2/dbs/rahtest/rahtest2.lrg'
var3=`echo /db2data3/dbs/rahtest/rahtest1.lrg'
var4=`echo /db2data3/dbs/rahtest/rahtest2.lrg'

when I tried to do

sed 's/$var/$var3' script.txt

it fails as / is there. I am using AIX.
My final files should be like this–

SET TABLESPACE CONTAINERS FOR 3
-- IGNORE ROLLFORWARD CONTAINER OPERATIONS
USING (
FILE '/db2data3/dbs/rahtest/rahtest1.lrg'  5120
);


SET TABLESPACE CONTAINERS FOR 4
-- IGNORE ROLLFORWARD CONTAINER OPERATIONS
USING (
  FILE   '/db2data3/dbs/rahtest/rahtest2.lrg'  5120
);

Best Answer

When there is a / in the text you can use a different character, for example a | as the separator for the sed arguments. Also, when using variables, you need to use double quotes ("") for the sed command because variables aren't expanded within single quotes. Try this:

var1='/db2data2/dbs/rahtest/rahtest1.lrg'
var2='/db2data2/dbs/rahtest/rahtest2.lrg'
var3='/db2data3/dbs/rahtest/rahtest1.lrg'
var4='/db2data3/dbs/rahtest/rahtest2.lrg'

sed -e "s|$var1|$var3|g" -e "s|$var2|$var4|" script.txt
Related Question