rong
rong

Reputation: 93

Regex for replacing 10th comma-separated column in CSV file

I have some files containing tens of thousand of rows of the format:

value1, value2, value3, value4, value5, value6, value7, value8, value9, value10
value1, value2, value3, value4, value5, value6, value7, value8, value9, value10
value1, value2, value3, value4, value5, value6, value7, value8, value9, value10

I want to replace value10 with a certain number (say x). So the result should be:

value1, value2, value3, value4, value5, value6, value7, value8, value9, x
value1, value2, value3, value4, value5, value6, value7, value8, value9, x
value1, value2, value3, value4, value5, value6, value7, value8, value9, x

I want to do this with regex. I have Sublime Text as a text editor.

Upvotes: 8

Views: 5308

Answers (2)

anubhava
anubhava

Reputation: 785256

You can search using this regex:

^((?:[^,]+,\s*){9})[^,]+

And replace using:

$1x

((?:[^,]+,\s*){9}) will match and group first 9 comma separated values that you can use in back-reference $1. [^,]+ outside parenthesis will match 10th value to be replaced.

RegEx Demo

PS: Verified that back-reference works in Sublime Test 3 as well.

Upvotes: 9

vks
vks

Reputation: 67968

^(?:[^,]+,\s*){9}\K[^,]+

You can use \K to discard 9 matches and then replace 10th.See demo.

https://regex101.com/r/kN5uS9/3

enter image description here

Upvotes: 6

Related Questions