Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 881
Peter Meier Avatar asked Mar 23 '12 11:03

Peter Meier


People also ask

How do you replace a character in awk?

awk has two functions; sub and gsub that we can use to perform substitutions. sub and gsub are mostly identical for the most part, but sub will only replace the first occurrence of a string. On the other hand, gsub will replace all occurrences.

Can we use awk and sed together?

Combining the Twoawk and sed are both incredibly powerful when combined. You can do this by using Unix pipes.


1 Answers

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
like image 115
potong Avatar answered Sep 20 '22 02:09

potong