Swapping values order for every line with vim

I have a .json file with a few thousands of locations, this is how it looks like:

{ "name" : "Wien", "location" : [ 48.2084671, 16.3730908 ], "zip_code" : "1000" }

{ "name" : "Himberg", "location" : [ 48.0809480921242, 16.4446190577947 ], "zip_code" : "2325" }


After generating that file, I just realised that MongoDB standard for geo coordinates is [longitude, latitude] but instead, in my file, I have [latitude, longitude], which means that I have to swap all this values. It is a file with 50k lines! I could probably quickly write a ruby script for that, but I am using a XXI century editor called Vim.

So how to achieve this inside of Vim. A substitution: find the two values and then replace with them swapped.

Best approach is to start by finding the exact targeted values. Because of the simplicity of this file, per line there is just one place where two numbers are separated by a comma and a space, our task is easy.

A regular expression to match this values can be something like:

/[0-9.]+, [0-9.]+/

Then we just need to save the values using ( ) for use during the substitution.

Everything inside will be after available in \1, \2, \3 and so on, for each pair of parenthesis from left to right.

In the end, and after adding the proper escaping, this is the magical line to globally swap the values in your file:

:%s/\([0-9.]\+\), \([0-9.]\+\)/\2, \1/g

My file now looks like:

{ "name" : "Wien", "location" : [ 16.3730908, 48.2084671 ], "zip_code" : "1000" }

{ "name" : "Himberg", "location" : [ 16.4446190577947, 48.0809480921242 ], "zip_code" : "2325" }


For more vim substitutions patters go here.

I so glad that I move back to vim.


comments powered by Disqus