Created
October 4, 2019 04:47
-
-
Save tjluoma/113ed4b45168a821d42ad7c372028737 to your computer and use it in GitHub Desktop.
use 'file' command to make sure files have the proper (expected) extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env zsh -f | |
# Purpose: use 'file' command to make sure image files have proper extension | |
# | |
# From: Timothy J. Luoma | |
# Mail: luomat at gmail dot com | |
# Date: 2019-10-04 | |
NAME="$0:t:r" | |
if [[ -e "$HOME/.path" ]] | |
then | |
source "$HOME/.path" | |
else | |
PATH='/usr/local/scripts:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin' | |
fi | |
for i in "$@" | |
do | |
if [[ -f "$i" ]] | |
then | |
# make sure we have the full path to '$i' | |
i=($i(:A)) | |
TYPE=$(file -b "$i" | awk '{print $1}') | |
case "$TYPE" in | |
JPEG) | |
# make it lowercase | |
EXPECTED_EXT='jpg' | |
;; | |
PNG) | |
# make it lowercase | |
EXPECTED_EXT='png' | |
;; | |
## If you want to add more filetypes, use `file -b "YourFileHere.ext" | awk '{print $1}'` | |
## and see what you get as output. Then replace 'FOO' with it and 'foo' with the | |
## proper extension. | |
# | |
# FOO) | |
# # make it lowercase | |
# EXPECTED_EXT='foo' | |
# ;; | |
*) | |
echo "$NAME: '$i' is type '$TYPE' but I don't know what to do with that." | |
continue | |
;; | |
esac | |
ACTUAL_EXT="$i:e:l" | |
if [[ "$EXPECTED_EXT" == "$ACTUAL_EXT" ]] | |
then | |
# the EXT that the file has is what it should have | |
echo " $NAME: '$i' has the proper extension." | |
continue | |
fi | |
## if we get here, then the extension does not match what we | |
## expected, which either means that it is a) missing or b) wrong | |
if [[ "$ACTUAL_EXT" == "" ]] | |
then | |
## there is no extension, so we need to add one | |
NEWNAME="$i.$EXPECTED_EXT" | |
else | |
## if we get here, the file has an extension | |
## but it is not the correct one | |
NEWNAME="$i:r.$EXPECTED_EXT" | |
fi | |
# initialize a counter | |
COUNT='0' | |
while [[ -e "$NEWNAME" ]] | |
do | |
# if there is another file with the same name we want to use | |
# add a digit to the filename | |
# so 'foo.jpg' would become 'foo.1.jpg' | |
# this loop will repeat if 'foo.1.jpg' also exists | |
((COUNT++)) | |
NEWNAME="$i:r.$COUNT.$EXPECTED_EXT" | |
done | |
# Once we get here we should be ready to rename the file | |
# but we use `-n` just to be safe | |
mv -vn "$i" "$NEWNAME" | |
fi | |
done | |
exit 0 | |
#EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment