Bash – How to replace the nth column/field in a comma-separated string using sed/awk

awkbashcsvreplacesed

assume I have a string

"1,2,3,4"

Now I want to replace, e.g. the 3rd field of the string by some different value.

"1,2,NEW,4"

I managed to do this with the following command:

echo "1,2,3,4" | awk -F, -v OFS=, '{$3="NEW"; print }'

Now the index for the column to be replaced should be passed as a variable. So in this case

index=3

How can I pass this to awk? Because this won't work:

echo "1,2,3,4" | awk -F, -v OFS=, '{$index="NEW"; print }'
echo "1,2,3,4" | awk -F, -v OFS=, '{$($index)="NEW"; print }'
echo "1,2,3,4" | awk -F, -v OFS=, '{\$$index="NEW"; print }'

Thanks for your help!

Best Solution

This might work for you:

index=3 
echo "1,2,3,4" | awk -F, -v OFS=, -v INDEX=$index '{$INDEX="NEW"; print }'

or:

index=3 
echo "1,2,3,4" | sed 's/[^,]*/NEW/'$index