Skip to content

Instantly share code, notes, and snippets.

@moregeek
Created December 17, 2015 21:20
Show Gist options
  • Save moregeek/04a199b68498ad99dc17 to your computer and use it in GitHub Desktop.
Save moregeek/04a199b68498ad99dc17 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
#
# GPLv3 / Stefan Morgenthaler, 2015;
#
# What?
#
# traverses a given directory down till no subdirectories are present. The pdf
# files within the 'last' directory are merged together and stored in the
# parents folder. The merged document uses the name of the directory, the pdfs
# where located in.
#
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "~ PDF MERGE BY FOLDER STRUCTURE ~"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
function main () {
local dir_now=$1;
local dir_lst=$(find ${dir_now} ! -path ${dir_now} -type d 2> /dev/null);
if [ -z "${dir_lst}" ]; then
pdfmerge ${dir_now}
else
for dir in ${dir_lst}; do
main $dir
done
fi
}
function pdfmerge () {
local path="$1"
local name="${path}/../$(basename ${path}).pdf";
[[ -f ${name} || ! -d ${path} ]] && return
echo "- Processing folder: ${path}"
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=${name} *.pdf \
&& rm -rf ${path};
}
main $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment