Take the 2-minute tour ×

I have a tex file containing instances of a command of the form \qdb{123} where the 123 can be generalised to any number of any length. I need to convert these statements into something more complicated: such as \text1{123}\text2{123}. The idea is that the number within the brackets is being used many times within the new output.

I need a method outside of the tex \newcommand function (this will be a pre processing step). Is sed the right tool, and if so, then how?

share|improve this question
Sed is a great tool for that. But, unless you spend a lot of effort for it, it will easily fail for cases like + linebreak in command + comments, etc. If you 'input' command is really that easy (no long text, no special cases), sed will do fine –  Rudolf Mühlbauer Oct 14 '12 at 18:32
The replace is to be relatively simple, no linebreaks and no comments. If I could do this as a \newcommend it would be easy; but I can't in this case. –  Geoff Oct 14 '12 at 18:34
add comment

2 Answers

up vote 1 down vote accepted

a simple solution could look like:


asldkfj aslfj ;aldfj \qdb{123} asdflk
\qdb{452345} somecommand \texttt{asdf}


asldkfj aslfj ;aldfj \text1{123}\text2{123} asdflk
\text1{452345}\text2{452345} somecommand \texttt{asdf}

by running (output to console, for testing):

sed -e 's/\\qdb{\([0-9]*\)}/\\text1{\1}\\text2{\1}/g' test.txt

by running (make changes directly on the file):


adapt the \\text1{\1}\\text2{\1} to suite your needs. \1 is the back-reference to the matched number.

needless to say: make sure to have a backup!

share|improve this answer
This works. I don't grasp the sed -i, I used sed -e and that was fine; but I had to output to a new file name. How can I simply rewrite over what I had? –  Geoff Oct 14 '12 at 18:54
@Geoff, updated accordingly –  Rudolf Mühlbauer Oct 14 '12 at 18:56
man sed describes the -i option, unsurprisingly. –  Rudolf Mühlbauer Oct 14 '12 at 19:08
add comment

If ruby is available, then perhaps something like this:

prompt> irb
>> s = "lorem \\qdb{123} ipsum \\qdb{123} lorem"
=> "lorem \\qdb{123} ipsum \\qdb{123} lorem"
>> s.gsub /\\qdb\{(\d+)\}/m, '\text1{\1}\text2{\1}'
=> "lorem \\text1{123}\\text2{123} ipsum \\text1{123}\\text2{123} lorem"

Backslash requires extra backslash escaping.

share|improve this answer
lots of backslashes, indeed ;) –  Rudolf Mühlbauer Oct 14 '12 at 18:45
add comment

Your Answer


