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


assume I have a string


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


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


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:

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


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