Option 1: sed
The stream editing tool, sed
, would be a natural first choice, but the problem is that sed
can't match non-greedy regular expressions.
We need a non-greedy regular expression here- to clarify why, let's consider
sed -r 's/|(.*)|/\\abs{\1}/g' myfile.tex
If we apply this substitution to a file that contains something like
$|a|+|b|\geq|a+b|$
then we'll get
$\abs{a|+|b|\geq|a+b}$
which is clearly not what we want- regular expression matches like this are greedy by default.
To make it non-greedy, we typically use .*?
, but the problem is that sed
does not support this type of match. Happily (thanks Hendrik) we can use the following instead
sed -r 's/\|([^|]*)\|/\\abs{\1}/g' myfile.tex
Once you're comfortable that it does what you want, you can use
sed -ri.bak 's/\|([^|]*)\|/\\abs{\1}/g' myfile.tex
which will overwrite each file, and make a back up first, myfile.tex.bak
Option 2: perl
We could, instead, use a little perl
one-liner:
perl -pe 's/\|(.*?)\|/\\abs{\1}/g' myfile.tex
When you're sure that you trust it is working correctly, you can use the following to overwrite myfile.tex
perl -pi -e 's/\|(.*?)\|/\\abs{\1}/g' myfile.tex
You can replace myfile.tex
with, for example, *.tex
to operate on all the .tex
files in the current working directory.
Details of perl
's switches are discussed here (for example): http://perldoc.perl.org/perlrun.html#Command-Switches
Edit -> Replace
what you're looking for? It has forward/backward search and is also case sensitive.\|([a-z]*)\|
in the "Find" field and\abs{\1}
in the Replace field (with Regexp checked).|
s. You could run the search to replace once the opening|
and once the closing|
. But I gather from your comment that this is not the case... My bad!:)
...and +1