find and replace multiple lines of string using sed

104 Views Asked by At

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!

5

There are 5 best solutions below

5
samthegolden On BEST ANSWER

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
0
Denis Zhukov On

pr might help here, please try this:

pr -m -t target input | sed -r 's/(Angle=)[^\s]+\s+/\1/'

Please note - this works for your first two showed files, your code assumes some different input - e.g. spaces around "=".

0
KamilCuk On

So I guess you want to paste files - marge files line by line. Then replace the field with a regex for example.

paste target_file input_file | sed 's/\(Angle=\)[^\t]*\t/\1/'
0
potong On

This might work for you (GNU sed):

sed '/Angle=/R inputFile' targetFile | sed '/Angle=/{N;s/=.*\n/=/}'

In the first sed invocation append the input line.

In the second sed invocation remove the original angle and the newline delimiter.

0
pshah On

So I was able to come up with this solution

#!/bin/bash

infile=$1
cp $infile ORIG_${infile}
grep "Angle = " $infile | sed 's/Angle = //g' | sort -n > temp.txt

iMax=`cat temp.txt | wc -l`
jMax=`grep -n "Angle = " $infile | tail -1 | sed 's/:.*//g'`

for ((i=1,j=12; i<=${iMax} && j<=${jMax};i+=1,j+=30));do
        a=`head -$i temp.txt | tail -1`
        sed -i "${j}s/Angle = .*/Angle = $a/g" $infile
done
rm temp.txt

Many thanks to william pursell for clarifying the syntax for incrementing var counts in bash.