Wednesday 2 January 2013

Replace in vim with placeholders


vim allows you to match strings in a file using regexs and replace them.

For example, to replace all instances of "foo" with "bar" in the file, you do:

:%s/foo/bar/g

What's actually more useful, is that we can use \( and \) to capture the values that matched by the pattern and use \1, \2, \3 and so on to put the matched values in the expression to substitute.

So, to swap columns 1 and 3 of a comma-separated file with 3 columns, we can use:

:%s/\([^,]*\),\([^,]*\),\([^,]*\)/\3,\2,\1/

No comments :