pratt
pratt

Reputation: 3

Replacing one variable with another variable in sed

I am trying to replace one variable with another interactively with sed -i. It seems to be very easy but for some reason is not working.

Let's say I have a file which has 1 column:

1
2
3
4
5
6
7
8
.
.

I want to assign these values into a variable and make an arithmetic operation on them which will be the new variable and then replace the previous variable with the new one. Something like the following:

for i in `awk '{print $1}' file.dat`;
do
        j=`echo $i | awk '{print ($1)*0.66}'`;
        sed -i "s/$i/$j/g" file.dat;
done

I expect to get the following:

0.66
1.32
1.98
2.64
3.3
3.96
4.62
5.28

But, here's what I get:

0.3.963.96
1.1.95.282
1.95.28
2.3.964
3.3
3.96
4.62
5.28

I know it's probably something very simple. But, my brain doesn't work today. Any help will be appreciated.

Upvotes: 0

Views: 200

Answers (1)

Barmar
Barmar

Reputation: 782467

When $i is 1, the first line of the file changes to 0.66.

Then when $i is 6, it replaces each of those 6 characters with 3.96, so that line becomes 0.3.963.96.

You need to change the regexp so it only matches entire lines:

sed -i "s/^$i\$/$j/g" file.dat;

^ and $ match the beginning and end of the line.

There doesn't seem to be much reason to used sed in this, though, you can do it entirely with awk:

awk '{print $1 * 0.66}' file.dat > newfile.dat

If you're using GNU awk it has an extension that can be used to modify the file in place.

gawk -i inplace '{print $1 * 0.66}' file.dat

Upvotes: 1

Related Questions