From f9e0d6565e8cbba4c879737bb74c4e94f68046c8 Mon Sep 17 00:00:00 2001 From: dabruh <11458706-dabruh@users.noreply.gitlab.com> Date: Tue, 15 Nov 2022 19:36:21 +0100 Subject: [PATCH] Create wrapper for 'convert' --- .local/bin/converta | 87 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100755 .local/bin/converta diff --git a/.local/bin/converta b/.local/bin/converta new file mode 100755 index 0000000..a934b53 --- /dev/null +++ b/.local/bin/converta @@ -0,0 +1,87 @@ +#!/bin/bash + +# converta +# +# Run `convert` over a directory and filter files by a particular pattern +# +# Example - Convert all ARW files in ~/Pictures to PNG: +# ./converta -d ~/Pictures -p '.*.ARW' -e PNG + +script_name="$(basename -- "$0")" +force=false + +function usage() { + echo "Usage: $script_name [OPTIONS]" + echo + echo "Options:" + echo " -h Display help" + echo " -d [DIRECTORY] Directory of files to process" + echo " -o [EXTENSION] Target extension" + echo " -l [LEVELS] Limit the amount of directory levels to process" + echo " -p [PATTERN] Extended regular expression pattern for filtering files" + echo + echo "Example:" + echo " $script_name -d ~/Pictures -o JPG -l 2 -p '.*.ARW$'" +} + +while getopts ":d:o:l:p:fh" arg; do + case $arg in + d) directory=$OPTARG ;; + o) extension=$OPTARG ;; + l) levels="-maxdepth $OPTARG" ;; + p) pattern=$OPTARG ;; + f) force=true ;; + h) + usage + exit 0 + ;; + :) + echo "$script_name: Must supply an argument to -$OPTARG." >&2 + usage + exit 1 + ;; + ?) + echo "Invalid option: -${OPTARG}." + echo + usage + exit 2 + ;; + esac +done + +[ -z "$directory" ] && usage && exit 1 +[ -z "$extension" ] && usage && exit 1 +[ -z "$pattern" ] && usage && exit 1 + +# Kill ourself with SIGINT upon receiving SIGINT: +trap ' + trap - INT # restore default INT handler + kill -s INT "$$" +' INT + +echo "Will $($force && echo "forcibly ")convert files in '$directory' that match '$pattern' to '$extension'" + +# shellcheck disable=SC2086 +while read -r input_path; do + file="$(basename "$input_path")" + output_path="${input_path%.*}.$extension" + addl_str="" + cvt=true + grep -Eq "$pattern" <<<"$file" || continue + + if [ -f "$output_path" ]; then + if [ "$(wc -c <"$output_path")" -eq 0 ]; then + addl_str=" (exists, 0 bytes)" + rm "$output_path" + elif ! $force; then + addl_str=" (already converted)" + cvt=false + else + addl_str=" (overwriting)" + rm "$output_path" + fi + fi + + echo "$input_path -> $output_path$addl_str" + $cvt && convert "$input_path" "$output_path" +done <<<"$(find "$directory" $levels -type f)"