maciek2791 maciek2791 - 4 months ago 12
Linux Question

Find X occurence of string in file and replace to static string

I need you help again. I need to find 3 and 4 occurrence of comma (accross the line) and replace with specific string, let's assume:

"Text","Text2","Text3","Text4","Text5"
"Text6","Text7","Text8","Text9","Text10"


Now, I would like to replace Text4,Text9,Text5,Text10 to eg. "Static"

"Text","Text2","Text3","Static","Static"
"Text6","Text7","Text8","Static","Static"


Which function should I use? Know that probably 'sed' is proper to do that, but how to count commas?

EDIT: (simpler version with only 3 occurence of comma)

I need to find ONLY 3 occurrence of comma (accross the line) and replace with specific string, let's assume:

"Text","Text2","Text3","Text4","Text5"
"Text6","Text7","Text8","Text9","Text10"


Now, I would like to replace Text4,Text9 to eg. "Static"

"Text","Text2","Text3","Static","Text5"
"Text6","Text7","Text8","Static","Text5"

Answer

This awk one-liner works for the given example. It changes the text in 4th and 5th columns/fields:

awk -F, -v OFS="," '{i=4;while(i<6)gsub(/\w+/,"Static",$(i++))}7' file