Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a serie of number on the same row in a configuration file?

Tags:

emacs

elisp

Let say I have a configuration file, and each lines contains space separated values. On on the column I have only zeros. Example:

... # there is more configuration before the interesting stuff:
0 0 file /dev/stdin 224.0.68.54:12131
0 0 file /dev/stdin 224.0.68.55:12102
0 0 file /dev/stdin 224.0.68.49:12333
0 0 file /dev/stdin 224.0.68.60:12184
0 0 file /dev/stdin 224.0.68.62:12888
0 0 file /dev/stdin 224.0.68.77:12001
0 0 file /dev/stdin 224.0.68.33:12973

Now I want to increment the second column with its index. that is I want this result:

0 0 file /dev/stdin 224.0.68.54:12131
0 1 file /dev/stdin 224.0.68.55:12102
0 2 file /dev/stdin 224.0.68.49:12333
0 3 file /dev/stdin 224.0.68.60:12184
0 4 file /dev/stdin 224.0.68.62:12888
0 5 file /dev/stdin 224.0.68.77:12001
0 6 file /dev/stdin 224.0.68.33:12973

How to to that in emacs lisp? Or any other Emacsen way of doing thing please?

like image 839
yves Baumes Avatar asked Jun 04 '13 14:06

yves Baumes


2 Answers

You can use the possibility to search and replace by an evaluated expression:

  • put the point on the first line to process
  • M-x query-replace-regexp RET
  • searched string: ^0 \([0-9]+\)
  • replace with: \,(format "0 %s" (+ \#1 \#))

The meaning is:

  • search a number preceded by a single zero at the beginning of the line
  • replace by the result of the evaluation where \#1 is the first matched group (like \1 but converted to number) and \# is the number of replacements already done (begins at 0 for the first replacement). The expression is evaluated for each match.

If the first number is not always a zero, I would use:

  • searched string: ^\([0-9]+\) \([0-9]+\)
  • replace with: \,(format "%s %s" \#1 (+ \#2 \#))
like image 129
Seki Avatar answered Nov 06 '22 10:11

Seki


You can use a macro with a counter to do that. You start defining a macro with F3 and end the definition with F4. While defining the macro, hitting F3 again will insert the value of the counter and increment it. After defining the macro, run it by hitting F4.

So in your case, move point to the beginning of the first interesting line, hit F3 C-f C-f C-d F3 C-n C-a F4 (i.e. remove the second zero, insert the counter, and move to the beginning of the next line). Then hit F4 as many times as needed to change all the lines.

If you need to change the value of the counter, use M-x kmacro-set-counter.

like image 35
legoscia Avatar answered Nov 06 '22 11:11

legoscia