bashsedgnu-sed

find and replace multiple lines of string using sed


I have an input file containing the following numbers

-45.0005
-43.0022
-41.002
.
.
.

I have a target txt file

line:12 Angle=30
line:42 Angle=60
line:72 Angle=90
.
.
.

Using sed I want to replace the first instance of Angle entry in the target file with the first entry from the input file, the second entry of Angle with the second entry of the input file so and so forth...

Expected output:

line:12 Angle=-45.005
line:42 Angle=-43.002
line:72 Angle=-41.002
.
.
.

This is what I have managed to write but I am not getting the expected output


a=`head -1 temp.txt`
#echo $a
sed  -i "12s/Angle = .*/Angle = $a/g" $procfile
for i in {2..41..1}; do
        for j in {42..1212..30}; do
                c=$(( $i - 1 ))
                #echo "this is the value of c: $c"
                b=`head -$i temp.txt | tail -$c`
                #echo "This is the value of b: $b"
                sed  -i "$js/Angle = .*/Angle = $b/g" $procfile 2> /dev/null
        done
done

Could you help me improve the script?

Thanks!


Solution

  • You may create an iterator i and then use it in sed to perform substitution in each line.

    i=0; 
    while read -r line; do 
       i=$((i+1)); 
       sed -i "${i}s/Angle=.*/Angle=${line}/g" $procfile; 
    done < temp.txt