Moving numbered files to add one entry

⇠ Back to Blog:Hacks

Say you have files like this:

lecture1.tex
lecture2.tex
lecture3.tex
...
lecture13.tex
lecture24.tex

and need to add a new lecture5! Maybe each file further comes with an header labelled after its numbering (say for lecture8.tex):

\chapter{Lecture 8 --- Complexity \& Interpretation of Quantum Mechanics}
\label{L8}

So if we want to add one file, all lectures from the old lecture5 onward should be moved one integer up (lecture5 becomes lectures6, etc.) and the headers also corrected accordingly.

The moving of files can be instructed with Mathematica:

Table["mv lecture" <> ToString[i] <> ".tex lecture" <> 
   ToString[i + 1] <> ".tex", {i, 24, 5, -1}] // TableForm

and copied/pasted as Plain Text (right-click) into a bash file:

#!/bin/bash

mv lecture24.tex lecture25.tex
mv lecture23.tex lecture24.tex
mv lecture22.tex lecture23.tex
mv lecture21.tex lecture22.tex
mv lecture20.tex lecture21.tex
mv lecture19.tex lecture20.tex
mv lecture18.tex lecture19.tex
mv lecture17.tex lecture18.tex
mv lecture16.tex lecture17.tex
mv lecture15.tex lecture16.tex
mv lecture14.tex lecture15.tex
mv lecture13.tex lecture14.tex
mv lecture12.tex lecture13.tex
mv lecture11.tex lecture12.tex
mv lecture10.tex lecture11.tex
mv lecture9.tex lecture10.tex
mv lecture8.tex lecture9.tex
mv lecture7.tex lecture8.tex
mv lecture6.tex lecture7.tex
mv lecture5.tex lecture6.tex

Then to increment the labeling in the files themselves, assuming that follows the structure I gave, that does it for one file (1st line the Chapter, 2nd the label):

perl -pi.bak -e 's/(\\chapter\{Lecture )(\d+)/$1.($2+1)/ge;' lecture8.tex
perl -pi.bak -e 's/(\\label\{L)(\d+)/$1.($2+1)/ge;' lecture8.tex

so for all files:

for f in lecture*.tex; do perl -pi.bak -e 's/(\\chapter\{Lecture )(\d+)/$1.($2+1)/ge;' "$f"; done
for f in lecture*.tex; do perl -pi.bak -e 's/(\\label\{L)(\d+)/$1.($2+1)/ge;' "$f"; done