Cool Examples

I will try and collect the coolest regular expressions that I’ve made here. Most of them will be for query-replace-regexp in [Emacs][] and may have to be adapted to the regexp syntax of your favorite language. In Emacs you can have arbitrary Elisp code executed when replacing, and thus you might find it difficult to translate the regexp into another language. Sorry :-)

Calculate running delta

I wanted to plot the disk usage of my daily backups with Gnuplot, and so I wanted a data file with the following format

# Date      Usage     Delta
2005-10-01  35685803  0
2005-10-02  35735650  49847

But I got the data from df and thus is looked like this

35685803        2005-10-01
35735650        2005-10-02

For the running delta we need a variable to store the last value. So initialize this with (setq l 35685803) in your *scratch* buffer. Then in the buffer with the data, execute query-replace-regexp (normally done by pressing “C-M-%”) and have it replace

\([0-9]+\) +\([0-9-]+\)


 \2 \1  \,(prog1 (- l \#1) (setq l \#1))

Nice, isn’t it? :-)

Aligning PHP constants

For the [PEL][] project I wanted to automatically align all the constants in class PelTag. It looks like this:

 * Large description of the InteroperabilityIndex tag.
const INTEROPERABILITY_INDEX                 = 0x0001;
/** ... */
const INTEROPERABILITY_VERSION                = 0x0002;
/** ... */
const IMAGE_WIDTH                             = 0x0100;
/** ... */
const IMAGE_LENGTH                           = 0x0101;
/** ... */
const BITS_PER_SAMPLE                         = 0x0102;

Here it is easy to see the mis-alignments, but in the real file the constants are separated by 10–20 lines of doc-comments and then it’s easy to loose sight of the correct alignment. So I wanted to automate it. Using the ability of [Emacs][] to execute Elisp code in the replacement it was easy: replace



const \1\,(make-string (- 60 (length \1)) ? )= \2;

That will make sure that all the equal signs are aligned 61 spaces after const. Adjust this number as appropriate for the lengths of the values of your constants.

One Comment

  1. Said:

    Hey, Martin..
    Denne one-liner til eksempel nr. 1 ;)

    awk ‘{if(NR==1)last=$1;print $2,$1,$1-last; last=$1}’ file.txt

Leave a comment