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

Posted by Peter Meier on Stack Overflow See other posts from Stack Overflow or by Peter Meier
Published on 2012-03-23T11:07:00Z Indexed on 2012/03/23 11:29 UTC
Read the original article Hit count: 240

Filed under:
|
|
|
|

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!

© Stack Overflow or respective owner

Related posts about bash

Related posts about replace