Reputation: 195
I have a comma delimited txt file, Is there a way regex can do search and replace ONLY after the nth comma, say, after 3rd comma so:
data1,data2,data3,regex,can,start,search,and,replace,here
Actually I need to perform this regex expresion
Find: ,key1,[^,]*
Replace: ,0,0
which I learned from Change the value of the key, then delete the key on comma delimited CSV using regex
Hope I can do the same operation ONLY after the nth comma
Thanks!
Upvotes: 1
Views: 2712
Reputation: 44023
I don't know what flavor of regex you're using, so you may have to fix it up a little (possibly escape parens/brackets), but your regex should look something like this:
^([^,]*,){n,}key1,[^,]*
Where [^,]*,
matches a field in the CSV and the comma after it, and ([^,]*,){n}
(replace n
with a number) matches that n times. For example, with sed you could use
sed 's/^\(\([^,]*,\)\{2\}\)key1,[^,]*,/\10,0,/' foo.csv
to replace key1,whatever
with 0,0
after the second comma.
If you mean after the nth or a later comma, use {n,}
instead of {n}
(that means "match n or more times).
Upvotes: 2