TransWikia.com

Deleting external/auxiliary files?

TeX - LaTeX Asked by Mats on May 20, 2021

Is there a way to make TeX delete files?

In my document a lot of auxiliary files are created and it would be wonderful to have them removed after their content has been used.

15 Answers

No, TeX itself can't delete files, just create or overwrite them. You need to use an external tool, like a LaTeX editor or Makefile to delete it for you. For example latexmk has a -c option which cleans up all auxiliary files.

I also use Makefiles under Linux which contain a clean rule which remove all auxiliary files. However, this isn't really a good way under Windows. At least if you are not used to it. You can find a list of auxiliary file extension in the thread Which auxiliary LaTeX files should be ignored by Version Control Software?).

However, you should note that removing auxiliary files often will have an negative impact on compile time. You will then be forced to compile your document 2-3 times or sometimes more often. Some (La)TeX compilers (e.g. MikTeX) also offer to place the auxiliary files in a different folder. This way they don't annoy you in your main folder.

Answered by Martin Scharrer on May 20, 2021

if you want get rid of those files in your document directory then use the optional argument -output-directory=whatever. Then all auxiliary files and the pdf are saved in that directory. For example what I use:

pdflatex -output-directory=target <file>

then my <file>.pdf is also in target, but I always use a softlink ln -s target/<file>.pdf then I have it in my documents directory, too. But as Martin already pointed out, deleting the auxiliary files makes only sense when you are really sure that your pdf file is finished.

If you want to copy the created pdf then use

usepackage{shellesc}
AtEndDocument{ShellEscape{cp /<target>/jobname.pdf /home/voss/}}

replace /home/voss/ with the directory where the pdf should be copied to. Then run the document with

pdflatex --shell-escape -output-directory=<target> <file>

However, writing a small script seems to be easier.

Answered by user2478 on May 20, 2021

Unfortunately, latexmk -c does not delete all generated files by default. For example, it does not delete files generated for glossary, acronym and index creation.

I managed to have latexmk -c delete more temporary files by creating a global .latexmkrc file (on Unix-like systems, put it into your home directory):

@generated_exts = qw(aux idx ind lof lot out toc acn acr alg glg glo gls ist);

In general, though, I prefer using the solution of Herbert, the -output-directory flag for latex, which is also supported by latexmk.

Answered by daniel kullmann on May 20, 2021

A variant of Herbert's answer:

In MiKTeX, you can specify an aux-directory, where all the auxiliary files (ergo basically everything except the pdf) are written, so use e.g.

pdflatex foo.tex --aux-directory="C:UsersJaneDoeDocumentsLaTeXauxiliaries-global"

As a result you'll get foo.pdf in whatever directory foo.tex is; foo.aux, foo.out and whatnot go in the aux-directory that you specified.

As has been noted, it's not recommended to delete the auxiliary files every time, but this is a neat way of "hiding" them and keeping your working directories from getting cluttered.

Since I don't use TeX Live (yet), I don't know if there's a comparable tweak for it.

Answered by doncherry on May 20, 2021

A TeXShop solution (Mac OS)

As others have mentioned, deleting auxiliary files as a matter of course is not usually a good idea, especially for complex documents. However, it is useful to be able to delete them manually when needed.

I use the following Applescript (written by Claus Gerhardt) saved as a macro in TeXShop. The script could also be adapted to other Mac editors. What I like about this script is that I can add new aux file extensions when needed, and it is able to deal with multiple part aux extensions such as -blx.bib, etc.

--AppleScript
-- Apply only to an already saved file
-- Claus Gerhardt, September 2006
(*This script gets the path of the frontmost (tex) document in TeXShop and removes the corresponding auxilary files the suffixes of which are listed in the list L. Beware of the quotation marks. The list L may contain suffixes to which no corresponding files exist.*)

my remove_auxiliaries()
on remove_auxiliaries()
    set L to {".aux", ".synctex.gz", ".fdb_latexmk", ".out", ".toc", ".bbl", ".blg", ".ind", ".sind", ".run.xml","-blx.bib",".log", ".end", ".1"} as list

    tell application "TeXShop"
        get path of document of window 1
        set fileName to result
    end tell

    set {baseName, texName, pdfName, namePath, dirName, dirNameunquoted, logName, logPath, rtfName, docName} to my setnamebbedit_rootn(fileName)


(*
tell application "TeXShop"
    close document docName
end tell
*)

    repeat with x in L
        try
            set shellScript to "cd " & dirName & ";"
            set shellScript to shellScript & "rm -f  " & baseName &  x
            do shell script shellScript
        end try
    end repeat

end remove_auxiliaries

on setnamebbedit_rootn(x)
    set n to (number of characters of contents of x)
    set fileNamequoted to quoted form of x
    set windowName to do shell script "basename " & fileNamequoted
    set m to (number of characters of contents of windowName)
    set dirName to quoted form of (characters 1 thru (n - m - 1) of x as string)
    set dirNameunquoted to (characters 1 thru (n - m - 1) of x as string)
    set theText to contents of windowName as string

    set n to (number of characters of contents of theText)
    set i to n as number

    repeat while i > 0
        if character i of theText is equal to "." then
            set m to i
            exit repeat
        else
            set i to (i - 1)
        end if
    end repeat

    set baseName to (characters 1 thru (m - 1) of theText as string)
    set texName to baseName & ".tex"
    set namePath to dirNameunquoted & "/" & baseName as string
    set pdfName to namePath & ".pdf" as string
    set rtfName to namePath & ".rtf" as string
    set logPath to namePath & ".log" as string
    set logName to baseName & ".log" as string

    set theFile to POSIX file x as string
    tell application "Finder"
        get displayed name of the file theFile
    end tell
    set docName to result


    return {baseName, texName, pdfName, namePath, dirName, dirNameunquoted, logName, logPath, rtfName, docName} as list
end setnamebbedit_rootn

Answered by Alan Munn on May 20, 2021

In case you are using Emacs with AucTeX, just run

M-x TeX-clean

This does not get rid of any temporary directories that are created, just files

Answered by Imad on May 20, 2021

FWIW, in ConTeXT you can delete the temporary files by passing --purge to the command line program context. Thus

  context --purge filename

will run context multiple times and then delete the auxiliary and log files.

Answered by Aditya on May 20, 2021

Another solution is to use the --clean flag from rubber.

rubber is, according to the project description, "a program whose purpose is to handle all tasks related to the compilation of LaTeX documents. This includes compiling the document itself, of course, enough times so that all references are defined, and running BibTeX to manage bibliographic references. Automatic execution of dvips to produce PostScript documents is also included, as well as usage of pdfLaTeX to produce PDF documents."

Let's say I have a mydoc.tex file which creates the following auxiliary files:

mydoc.aux   mydoc.ilg   mydoc.log
mydoc.idx   mydoc.ind   mydoc.toc

besides of course of mydoc.pdf. When running the following command

rubber --clean mydoc

only two files remain:

mydoc.pdf mydoc.tex

If I want to have only mydoc.tex, using rubber --pdf --clean mydoc will do the job.

According to the manual:

  • --clean: Remove all files produced by the compilation, instead of building the document. This option is present in rubber only. It applies to the compilation as it would be done with the other options of the command line, i.e. saying rubber --clean foo will not delete foo.ps, while saying rubber --ps --clean foo will.

In case you need some "advanced" cleanup process, there's also a clean directive. A directive is a line like

% rubber: cmd args

The line must begin with a %, then any sequence of % signs and spaces, then the text rubber: followed by zero or more spaces and a directive name, possibly followed by spaces and arguments.

Lets say we have a dummy.txt file generated on every compilation of mydoc.tex. I want to get rid of it, so I add the following directive in mydoc.tex:

% rubber: clean dummy.txt
documentclass{article}
...

Now, when running rubber --clean mydoc, dummy.txt will be removed. According to the manual:

  • clean <file> Indicates that the specified file should be removed when cleaning using --clean.

There we go, a clean project folder. :)

Answered by Paulo Cereda on May 20, 2021

For manual deletion, the latex editor TeXstudio (and probably its parent TeXmaker as well) contains an option "Clean Auxiliary Files" in the Tools menu.

As advised in other answers, aux file deletion should only be done manually when document no longer needs any further editing.

Answered by Ammar on May 20, 2021

You can also do Windows shell scripting with LaTeX as follows.

Main input file

Let main.tex be your main input file that you want to compile and delete its auxiliary files.

% main.tex
documentclass[12pt]{article}
usepackage[a6paper,margin=2cm,landscape]{geometry}
begin{document}
begin{equation}
E=mc^2
label{eq:Einstein}
end{equation}
newpage
See equation~ref{eq:Einstein} on page~pageref{eq:Einstein}.
end{document}

Shell scripting input file

Create additional input file for shell scripting as follows.

% host.tex
documentclass[preview,border=12pt]{standalone}

usepackage{pgffor,graphicx}

foreach x in {1,...,3}{immediatewrite18{latex main && dvips -t unknown main && ps2pdf -dAutoRotatePages=/None main.ps}}

foreach ext in {aux,log,dvi,ps}{immediatewrite18{cmd /c del main.ext}}

begin{document}
pdfximage{main.pdf}
foreach ip in {1,...,thepdflastximagepages}{fbox{includegraphics[page=ip,scale=0.5]{main}}endgraf}
end{document}

The code snippet below

foreach ext in {aux,log,dvi,ps}{immediatewrite18{cmd /c del main.ext}}

removes the auxiliary files.

Compile with pdflatex -shell-escape

Compile the host.tex with pdflatex -shell-escape host. And you will get an output as follows to make sure everything was done properly.

enter image description here

Complete code

The following code simulates everything in one invocation of pdflatex. Make sure to compile it with pdflatex -shell-escape host.

% host.tex
documentclass[preview,border=12pt]{standalone}

usepackage{filecontents}
begin{filecontents*}{main.tex}
documentclass[12pt]{article}
usepackage[a6paper,margin=2cm,landscape]{geometry}
begin{document}
begin{equation}
E=mc^2
label{eq:Einstein}
end{equation}
newpage
See equation~ref{eq:Einstein} on page~pageref{eq:Einstein}.
end{document}
end{filecontents*}

usepackage{pgffor,graphicx}

foreach x in {1,...,3}{immediatewrite18{latex main && dvips -t unknown main && ps2pdf -dAutoRotatePages=/None main.ps}}

foreach ext in {aux,log,dvi,ps}{immediatewrite18{cmd /c del main.ext}}

begin{document}
pdfximage{main.pdf}
foreach ip in {1,...,thepdflastximagepages}{fbox{includegraphics[page=ip,scale=0.5]{main}}endgraf}
end{document}

Answered by kiss my armpit on May 20, 2021

There is @paulo's awesome arara (The cool TeX automation tool) without which I can't imagine working anymore. It has a predefined clean directive that allows to specify which files should be seleted after compilation. The following file called test.tex would be compiled twice and then the aux and the toc file would be removed:

% arara: pdflatex
% arara: pdflatex
% arara: clean: { files: [ test.aux , test.toc ] }
documentclass{article}
begin{document}

tableofcontents

section{Test}

foo

end{document}

As I found it tedious to specify the whole filename that should be removed (I had to prepare about 60 different small files where I wanted the directory cleaned up after successfull compilation) I asked @paulo if there was an arara equivalent for jobname

% arara: clean: { files: [ jobname.aux, jobname.log ] }

that would allow me simply copying the arara directives from one file to the next. He came up with the following nice rule (thanks again @paulo):

!config
identifier: remove
name: Remove
command: <arara> @{remove}
arguments:
- identifier: remove
  default: <arara> @{isNotEmpty(item, isWindows("cmd /c del", "rm -f").concat(' "').concat(getBasename(file))concat('.').concat(item).concat('"'))}

With this rule correctly installed the above example becomes

% arara: pdflatex
% arara: pdflatex
% arara: remove: { items: [ aux , toc ] }
documentclass{article}
begin{document}

tableofcontents

section{Test}

foo

end{document}

Answered by cgnieder on May 20, 2021

There is a (slightly hacky) solution which uses latexmk only to clean up:

pdflatex <file>
latexmk -c

Answered by Augustin on May 20, 2021

I'm on linux and I have written the following bash script that is always running:

#!/bin/bash

inotifywait -m -r ~/Documents -e create |
    while read path action file; do
      echo "$file $path $action";
      if [[ "$file" =~ .*.(aux|log) ]]
        then
        if [[ ! -f "$path"/.hidden ]] || ! (grep -Fxq "$file" "$path"/.hidden)
           then
           echo "hide file"
           echo "$file" >> "$path"/.hidden
        fi
      fi
    done

What this does: It first looks in the home folder with the documents if any documents get created. If the created document is an aux or a log, it add the file to a special hidden file so that the file explorer (nemo in my case) knows it should not show the file.

The advantage is that for latex everything works as it should. Not all file explorers support this, but when it does, this is a nice solution.

You can modify this for your own use.

Answered by ppareit on May 20, 2021

Cleaning whole directories / Windows only solution

I'm drafting documents for a certain project in a project directory. Different documents, different version, no versioning system like e.g. git. After a while the project ends and I'll never again compile exactly these *.tex files in this directory.

At this time, I'll copy a powershell file into the project directory, called "Putzdienst.ps1" = cleaningservice.ps1.

It removes all the files I no longer need. Works only on Windows, but of course a Linux or Mac OS X solution wouldn't be much longer. You can simply add all the file types you'd like to delete. Beware, these files will just be deleted ! No backup, no waste paper basket -- GONE!

This is the code of "Putzdienst.ps1", adapt to your needs:

    function Get-ScriptDirectory{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    Split-Path $Invocation.MyCommand.Path
}

$path = (Get-ScriptDirectory)

cd $path


remove-item  *.log |% {remove-item $_}

get-childitem *.toc |% {remove-item $_}

get-childitem *.gz |% {remove-item $_}

get-childitem *.aux |% {remove-item $_}

get-childitem *.nav |% {remove-item $_}

get-childitem *.out |% {remove-item $_}

get-childitem *.synctex |% {remove-item $_}

get-childitem *.synctex.gz |% {remove-item $_}

get-childitem *.tmp |% {remove-item $_}

get-childitem *.4ct |% {remove-item $_}

get-childitem *.4tc |% {remove-item $_}

get-childitem *.anl |% {remove-item $_}

get-childitem *.lg |% {remove-item $_}

get-childitem *.idv |% {remove-item $_}

get-childitem *.xref |% {remove-item $_}

Answered by Keks Dose on May 20, 2021

For TexMaker, a convenient option is to check Launch the "Clean" tool when exiting TeXmaker:

enter image description here

Answered by qwr on May 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP