Question

I'm trying to substitute a field from a string with 13 fields separated with commas. I have both the position I want to substitute and the new value I want to give to that position in separated variables. Using bash.

#Original string:
THR=’0,0,0,0,0,0,0,0,0,0,0,0,0’
#Position I want to manipulate:
pos=’3’
#Value I want to write in the field "pos"
val=’8.73’

# What I'm trying to do:
echo $THR | awk -v chawk=$pos -v thrawk=$val -F',' '{ print; $chawk=$thrawk; print }'

THR should be '0,0,8.73,0,0,0,0,0,0,0,0,0,0'

Cheers

Was it helpful?

Solution

You had it nearly, remove the $ infront of $thrawk

awk -v chawk=$pos -v thrawk=$val -F',' '{ print; $chawk=thrawk; print }' OFS=\. <<< $THR
0,0,0,0,0,0,0,0,0,0,0,0,0
0.0.8.73.0.0.0.0.0.0.0.0.0.0

To restore it to the variable THR

THR=0,0,0,0,0,0,0,0,0,0,0,0,0
THR=$(awk -v chawk=$pos -v thrawk=$val -F',' '{ $chawk=thrawk; print }' OFS=\. <<< $THR)
echo $THR
0.0.8.73.0.0.0.0.0.0.0.0.0.0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top