Ask people to help me write a script that replaces all the math formulas $$ ... $$ into \ [... ] in texstudio. Thank you!


Here are a few ways that might help to get you started.

We'll start with the following file, say myfile.tex:


before text $$a^2+b^2=4$$ and $$c^2$$

d^2+e^2 = f^2
and also $$ g^2
$$ and some inline math: $h^2$

in each of the following, the output is:


before text \[a^2+b^2=4\] and \[c^2\]

d^2+e^2 = f^2
and also \[ g^2
\] and some inline math: $h^2$

option 1: a perl one liner

perl -p0 -e 's/\$\$(.*?)\$\$/\\\[$1\\\]/sg' myfile.tex > output.tex

See https://perldoc.perl.org/perlrun.html, for example, for details of perl switches.

option 2: using a perl script

Using the following script, and the command

perl replace.pl myfile.tex > output.tex


#!/usr/bin/env perl

use strict;
use warnings;

# read the file into the Document body
my @lines;
my $fileName = $ARGV[0];

# if the file exists, read it into an array
if(-e $fileName){
    open(MAINFILE, $fileName) or die "Could not open input file, $fileName";
    push(@lines,$_) while(<MAINFILE>);

# join the lines up
my $body = join("",@lines);

# make the substitution
$body =~ s/\$\$

# output the body
print $body;


option 3: using latexindent

Using latexindent which should be available as part of your LaTeX distribution, you can use the following YAML settings file:


    substitution: |-

and then call it with

latexindent.pl -rr -l=Anh.yaml myfile.tex -o=output.tex
| improve this answer | |
  • Not so simple. You have to handle cases like For $x$$=$$y$, we have no displays. – Donald Arseneau Apr 18 at 18:28
  • @DonaldArseneau an interesting test case... I wonder: is it realistic...? Also, you'll note that my post said help get you started... – cmhughes Apr 18 at 18:37
  • to whoever gave -1: thanks! – cmhughes Apr 18 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.