Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine multiple string replacement awk commands into one

Tags:

awk

I have two separate awk commands that replaces the third column of specific rows of the destination_file with the third column of specific rows of the source file. The commands work but is cumbersome with a lot of IO operations. Is there a way to combine the awk commands into one?

The commands I have at the moment are:

z2=$(awk 'NR==12 { print$1 }' ../source_folder/source_file)
z3=$(awk 'NR==14 { print$1 }' ../source_folder/source_file)


awk -v z2=$z2 'NR==10{$3=z2} 1' destination_file > temp && mv temp destination_file
awk -v z3=$z3 'NR==11{$3=z3} 1' destination_file > temp && mv temp destination_file

As an expansion to this problem, the rows I obtain values for z2, z3, z4 ... are from NR==12, 14, 16 ... and the rows in the destination_file that I want to replace are NR==10, 11, 12 ...; is there a way to write a sequence to do this string replacement operation instead of listing all the z1, z2, z3 ...?

like image 526
Jacek Avatar asked Mar 02 '26 19:03

Jacek


1 Answers

You could combine both of your programs into one. Have only 1 awk program to check both conditions NR==10 and NR==11 and do respective assignments of values to respective fields as per condition. This will save output into output file then.

z2=$(awk 'NR==12 { print$1 }' ../source_folder/source_file)
z3=$(awk 'NR==14 { print$1 }' ../source_folder/source_file)

awk -v z2="$z2"  -v z3="$z3" 'NR==10{$3=z2} NR==11{$3=z3} 1' destination_file > temp && mv temp destination_file
like image 71
RavinderSingh13 Avatar answered Mar 05 '26 09:03

RavinderSingh13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!