emacs rocks

Tuesday 2 February 2010

I had a boring text editing task. I'm using a text file that refers to components by a number and after writing it I realised that I need those component numbers to be incrementing.

I had:

Bus.con = [
 101   138  1  0  2  1;
 102   138  1  0  2  1;
...
 124   138  1  0  2  1;
 201   138  1  0  2  1;
 202   138  1  0  2  1;
...
];

Shunt.con = [
 106  100  138  60  0  -1  1;
 206  100  138  60  0  -1  1;
 306  100  138  60  0  -1  1;
];

I wanted:

Bus.con = [
  1  138  1  0  2  1;
  2  138  1  0  2  1;
...
 24   138  1  0  2  1;
 25   138  1  0  2  1;
 26   138  1  0  2  1;
...
];

Shunt.con = [
  6  100  138  60  0  -1  1;
 30  100  138  60  0  -1  1;
 54  100  138  60  0  -1  1;
];

One problem is that the component number might be the same as a parameter (which I don't want to change). Two tools here:

  1. re-builder - interactively build a regular expression. 
  2. (query)-replace-regexp - replace a regexp with another 
  3. elisp in regexps - do anything with a regexp
This led to the following three replacements:
replace " 1\([0-2][0-9]\) " with " \1 "
replace " 2\([0-2][0-9]\) " with " \,(+ 24 string-to-int \1)) "
replace " 3\([0-2][0-9]\) " with " \,(+ 48 string-to-int \1)) "
by doing it as a query I made sure I was only replacing the correct stuff. 

I even had time to write this blog post.