Skip to content

Instantly share code, notes, and snippets.

@tjluoma
Created December 24, 2019 04:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjluoma/e4fe87ebf29ce16141ab8ea0fd491948 to your computer and use it in GitHub Desktop.
Save tjluoma/e4fe87ebf29ce16141ab8ea0fd491948 to your computer and use it in GitHub Desktop.
Use `mdls` on macOS to get the number of pages in PDF files
#!/usr/bin/env zsh -f
# Purpose: count PDF pages with a variety of tools
#
# From: Timothy J. Luoma
# Mail: luomat at gmail dot com
# Date: 2019-12-23
NAME="$0:t:r"
if [[ -e "$HOME/.path" ]]
then
source "$HOME/.path"
else
PATH="$HOME/scripts:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin"
fi
for i in "$@"
do
EXT="$i:e:l"
# if this file does not end in '.pdf' then skip it
[[ "$EXT" != "pdf" ]] && continue
# we try to get the page count with `mdls`
PAGE_COUNT=$(mdls -raw -name kMDItemNumberOfPages "$i")
# if mdls cannot get the page count it will return '(null)'
if [[ "$PAGE_COUNT" == "(null)" ]]
then
# we were given more than one arg, so we do need to output the filename
echo "$i: Unable to determine page count." >>/dev/stderr
else
if [[ "$PAGE_COUNT" == "1" ]]
then
echo "$i (1 page)"
else
echo "$i (${PAGE_COUNT} pages)"
fi
fi
done
exit 0
#EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment