Skip to content

Instantly share code, notes, and snippets.

@mujdat
Created February 4, 2026 13:12
Show Gist options
  • Select an option

  • Save mujdat/a75fc2fe680c4e6d6759cbf6644f4aed to your computer and use it in GitHub Desktop.

Select an option

Save mujdat/a75fc2fe680c4e6d6759cbf6644f4aed to your computer and use it in GitHub Desktop.
pdfg
pdfg() {
local recursive=0
local copy_to=""
local args=()
# parse all args, flags can appear anywhere
while (( $# )); do
case "$1" in
-r|--recursive)
recursive=1
shift
;;
--copy-to)
shift
copy_to="$1"
[[ -n "$copy_to" ]] || { echo "pdfg: --copy-to needs a directory" >&2; return 2; }
shift
;;
--)
shift
args+=("$@")
break
;;
*)
args+=("$1")
shift
;;
esac
done
if (( ${#args[@]} < 2 )); then
echo "Usage:" >&2
echo " pdfg [options] <files/dirs...> \"pattern\"" >&2
echo "Options:" >&2
echo " -r, --recursive search directories recursively" >&2
echo " --copy-to <dir> copy matched PDFs into dir" >&2
return 2
fi
local pattern="${args[-1]}"
local targets=("${args[@]:0:${#args[@]}-1}")
[[ -n "$copy_to" ]] && mkdir -p -- "$copy_to"
_search_one() {
local f="$1"
pdftotext "$f" - 2>/dev/null |
grep --with-filename --label="$f" --color=always -n -- "$pattern"
}
if (( recursive )); then
find "${targets[@]}" -type f -name '*.pdf' -print0 |
while IFS= read -r -d '' f; do
if out="$(_search_one "$f")"; then
printf '%s\n' "$out"
[[ -n "$copy_to" ]] && cp -n -- "$f" "$copy_to/"
fi
done
else
for f in "${targets[@]}"; do
[[ -f "$f" && "$f" == *.pdf ]] || continue
if out="$(_search_one "$f")"; then
printf '%s\n' "$out"
[[ -n "$copy_to" ]] && cp -n -- "$f" "$copy_to/"
fi
done
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment