I want to make Latex table code from Unix cal output, e.g. It should look like:
Mo & Tu & We & Th & Fr \\
& & 1 & 2 & 3 \\
6 & 7 & 8 & 9 & 10 \\
13 & 14 & 15 & 16 & 17 \\
20 & 21 & 22 & 23 & 24 \\
27 & 28 & & & \\
I’ve come up with the following solution:
cal | sed -e '1d; /^$/d; s/^\(...\)\?\(...\)\?\(...\)\?\(...\)\?\(...\)\?\(...\)\?.*/\2 \& \3 \& \4 \& \5 \& \6 \\\\/'
Works like a charm! But I’m not sure if the result is defined. Wouldn’t it be correct behaviour, e.g. for the first group to match the empty string, and for the second group to match the first three chars of any line (instead of chars 4-6)? And if not, would there be some switch to make a variation of it a correct behaviour (so I can know how to avoid it / control the behaviour)?
My regex is fulfilling the spec. That is because the expression tree is expanded greedily from the left, so if there is a possible match which includes the first subexpression, then it will take this one.