Can I replace all instances of one string expressions in the TeX files in one directory?

For example, let's say I want to replace all \frac with \myfrac in more than one file simultaneously.

  • 3
    Alternatively, you could let the files keep using the original \frac{}{} and use \let\OldFrac\frac, and \let\frac\myfrac. And if \myfrac was originally using frac, replace the occurrence of frac with OldFrac within the definition of \myfrac. – Peter Grill May 4 '12 at 14:59
  • 1
    This looks very borderline for on-topic, as it's about editors/text manipulation rather than TeX. @PeterGrill's approach is TeX-based, but it's not clear that the question is rally about that method at all. – Joseph Wright May 5 '12 at 6:45

Which operating system are you using? If you're using a *nix based operating system (Mac included), it's probably easiest to do this out of TeX, in the command line / terminal:

find /home/my/directory -type f -exec sed -i 's/OldString/NewString/g' {} \;

(using a combination of find and sed.)

So you'd need:

find /home/my/directory -type f -exec sed -i 's/frac/myfrac/g' {} \;

Hope this helps.

  • 1
    Thanks. As remark for others, at first it didn't work and I had to add the two symbols "" after -i as suggested here. – Nikolaj-K May 4 '12 at 16:07
  • Assume that only applies to Mac users? – Savara May 4 '12 at 17:27
  • Mac Version 10.5.8 here, I don't know how far this reaches. – Nikolaj-K May 4 '12 at 19:13
  • 2
    Why not just sed 's/something/else/g' *.tex? Shell-agnosticism? – morbusg May 4 '12 at 19:52

Most advanced text editors have a replace feature that can apply to a whole set of files at once.

For example, Notepad++ on Windows provides this feature. As mentionned in another response to this question, if you are using a *nix-based system, you could quite easily use the command line.


If you use Vim, you can try the following: First open one of your .tex files in vim.

Load the other .tex files from the same directory by opening them in hidden buffers:

:args *.tex

Now all the *.tex files in the directory are loaded into (hidden) buffers. You can apply a standard substitution command to each of these files by issuing the following command:

:argdo %s/string1/string2/g | update

The % is the range (entire file), s denotes the substitution command, string1 is found and replaced by string2 on each line, and g indicates that this is done globally (so not just the first instance on each line). The last part | update will automatically save all the files after the substitution is complete.

Because the backslash is a "special" character, you need to escape it with another backslash. In your case, you would issue the command:

:argdo %s/\\frac/\\myfrac/g | update

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.