Skip to content

Instantly share code, notes, and snippets.

@NigoroJr
Last active June 16, 2020 19:52
Show Gist options
  • Save NigoroJr/c86a42c30a4444eda82c70a0818ba063 to your computer and use it in GitHub Desktop.
Save NigoroJr/c86a42c30a4444eda82c70a0818ba063 to your computer and use it in GitHub Desktop.
#!/bin/sh
# Usage:
# ./rename_screenshots.sh -h
#
# Optios:
# -h Show help
# -d Directory where screenshots are saved
# -p Pattern of the files
# -s Remove spaces from file names
# -f Run in foreground
#
# Example:
# $ ./rename_screenshots.sh screen_shot &
# $ disown
if ! type fswatch >/dev/null 2>&1; then
echo 'fswatch not found' 1>&2
exit 1
fi
DEFAULTS_COMMAND="defaults read com.apple.screencapture"
LOCATION="$( $DEFAULTS_COMMAND location 2>/dev/null || echo "$HOME/Desktop" )"
DEFAULT_NAME="$( $DEFAULTS_COMMAND name 2>/dev/null || echo "Screen Shot" )"
EXT="$( $DEFAULTS_COMMAND type 2>/dev/null || echo "png" )"
PATTERN="^$DEFAULT_NAME.*\.$EXT$"
ONLY_REMOVE_SPACES=0
# In case of duplicates
SUFFIX=1
RUN_IN_FOREGROUND=0
VERBOSE=0
while getopts 'hp:d:sfv' flag; do
case "$flag" in
p)
PATTERN="$OPTARG"
;;
d)
LOCATION="$OPTARG"
;;
s)
ONLY_REMOVE_SPACES=1
;;
f)
RUN_IN_FOREGROUND=1
;;
v)
VERBOSE=1
;;
h)
echo "Usage: $0 [-h] [-p <regex>] [-d <dir to monitor>] " \
"[-s] [name]"
exit 0
esac
done
shift $(( $OPTIND - 1 ))
NAME="${1:-"ss"}"
__monitor_screenshots() {
fswatch -0 "$LOCATION" | while read -d $'\0' full_path; do
BASENAME="$( basename "$full_path" )"
DIRNAME="$( dirname "$full_path" )"
if [ -n "$( echo "$BASENAME" | grep -o "$PATTERN" )" ] && [ -f "$full_path" ]; then
if [ "$ONLY_REMOVE_SPACES" -eq 1 ]; then
mv "$full_path" "$DIRNAME/$( echo "$BASENAME" | sed -e 's/ //g' )"
else
# First try without prefix
NEW_NAME="$NAME.$EXT"
while [ -f "$DIRNAME/$NEW_NAME" ]; do
NEW_NAME="$NAME$SUFFIX.$EXT"
SUFFIX="$( echo "$SUFFIX + 1" | bc)"
done
mv "$full_path" "$DIRNAME/$NEW_NAME"
if [ "$VERBOSE" -eq 1 ]; then
echo "$full_path"
echo " => $NEW_NAME"
fi
fi
fi
done
}
if [ "$RUN_IN_FOREGROUND" -eq 1 ]; then
__monitor_screenshots
else
__monitor_screenshots &
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment