Skip to content

Instantly share code, notes, and snippets.

@kidanger
Created September 11, 2018 09:45
Show Gist options
  • Select an option

  • Save kidanger/150e86931264c9aec69e226c13e4cdd7 to your computer and use it in GitHub Desktop.

Select an option

Save kidanger/150e86931264c9aec69e226c13e4cdd7 to your computer and use it in GitHub Desktop.
The ugliest script to convert trimmed images in latex to cropped images.
#!/usr/bin/env bash
file=$1
dir=$(dirname $file)
nfile=${file}.new
cp $file $nfile
cat $file |
grep -E '^[^%]*\includegraphics.*trim={.*}.*$' |
sed 's/^.*\includegraphics[[^\]]*trim={\([[:digit:]]*\)px \([[:digit:]]*\)px \([[:digit:]]*\)px \([[:digit:]]*\)px}.*]{\([^}]*\).*}$/\1 \2 \3 \4 \5 \0/' |
while read -r a b c d f line; do
fdir=$(dirname $f)
fname=$(basename $f)
ofname=$fname
add=0
if [ ! -f $dir/$f ]; then
if [ "$(ls $dir/$f.* | wc -l)" -ne 1 ]; then
echo /!\\ $dir/$f not processed. crop $a $d -$c -$b $f $nf
continue
fi
f=$fdir/$(basename $(ls $dir/$f.*))
fname=$(basename $f)
fi
nf=${fdir}/trim_${a}_${b}_${c}_${d}_${ofname}
newline=$(echo $line | sed "s/trim={${a}px ${b}px ${c}px ${d}px},\?//" | sed "s|\(\includegraphics.*\){[^}]*}|\1{${nf}}|")
python3 -c "s=open('$nfile', 'r').read().replace('${line//\\/\\\\}', '${newline//\\/\\\\}');open('$nfile','w').write(s)"
nf=${fdir}/trim_${a}_${b}_${c}_${d}_${fname}
# requires crop from imscript
crop $a $d -$c -$b $dir/$fdir/$fname $dir/$nf
echo $dir/$f
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment