Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 431
rong Avatar asked Sep 04 '15 06:09

rong


2 Answers

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.

like image 176
anubhava Avatar answered Nov 15 '22 06:11

anubhava


^(?:[^,]+,\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

like image 41
vks Avatar answered Nov 15 '22 08:11

vks