Featured image of post How I create LaTeX code for inserting images automatically

How I create LaTeX code for inserting images automatically

A little bash script for you ♥️

When I create my LaTeX documents, I’m heavy on figures. It is a problem when I want to insert them through code in good order and with an appropriate size. With that in mind, I created a little bash script. It searches through a directory of all the .pdf files (I save all of my figures in this format, you can change it to .png or some other LaTeX-friendly image format). The script goes as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
rm -f multiFigure.md
touch multiFigure.md

# $1 is the prefix, could include the subdirectory or a prefix for a name

echo %********** >> multiFigure.md
for filename in $1*.pdf; do # 
  echo '\begin{figure*}[ht!]' >> multiFigure.md
  echo '    \centering' >> multiFigure.md
  echo '    \begin{subfigure}[b]{0.29\linewidth}' >> multiFigure.md
  echo '        \centering' >> multiFigure.md
  echo '        \includegraphics[width = 0.9\textwidth]{'"$filename"'}' >> multiFigure.md
  echo '        \caption{}' >> multiFigure.md
  echo '        \label{fig:'"${filename%.*}"'}' >> multiFigure.md
  echo '    \end{subfigure}\quad' >> multiFigure.md
  echo '    \caption{}' >> multiFigure.md
  echo '    %\label{fig:'"${filename%.*}"'}' >> multiFigure.md
  echo '\end{figure*}' >> multiFigure.md
done
echo %********** >> multiFigure.md

cat multiFigure.md

It writes the code into the multiFigure.md file. You can copy and paste the code wherever you want and edit sizes, change positions, and everything without worrying about the names of the files. It goes through files alphabetically. If you have the names numbered, the output will respect that.

They are some prerequisites inside LaTeX. They are:

1
2
\usepackage{caption}
\usepackage{subcaption}

Example

With the bash script, you can create results like this with minimal configuration:

Now you can create code automatically to solve your image needs in LaTeX.


Invitame un café en cafecito.app

Built with Hugo
Theme Stack designed by Jimmy