Skip to content

Instantly share code, notes, and snippets.

@elisboa
Created May 17, 2021 01:11
Show Gist options
  • Save elisboa/0fedb8f60db1a4003261f929b69ffc74 to your computer and use it in GitHub Desktop.
Save elisboa/0fedb8f60db1a4003261f929b69ffc74 to your computer and use it in GitHub Desktop.
Sort Files Shell Script
#!/usr/bin/env bash
setvars()
{
ORIGIN_PATH="."
DESTIN_PATH="."
Full_File_Path="."
File_Year="0001"
File_Month="01"
File_Day="01"
File_row=""
File=""
}
check_args()
{
echo "Number of arguments: ${#}"
if [[ ! -z "${@}" ]] && [[ ${#} == 2 ]]
then
echo "Arguments passed: $@"
ORIGIN_PATH="${1}"
DESTIN_PATH="${2}"
else
echo "Usage: ${0} ORIGIN_DIR DESTINATION_DIR"
exit 1
fi
}
monthnumber() {
month=${1}
months="janfevmarabrmaijunjulagosetoutnovdez" # THIS IS IN PORTUGUESE, CHANGE TO YOUR LANGUAGE BEFORE USING IT
tmp=${months%%$month*}
month=${#tmp}
monthnumber=$((month/3+1))
printf "%02d\n" $monthnumber
}
build_file_list()
{
echo "Building file list"
ls -ltrah ${ORIGIN_PATH}/*.{CR2,JP*G} 2> /dev/null | grep -v ^total | while read File_row
do
echo "Parsing file row ${File_row}"
File_Month=$(echo ${File_row} | awk '{print $6}')
#echo "File_Month ${File_Month}"
monthnumber=$(monthnumber ${File_Month})
#echo "Month number ${monthnumber}"
File_Day=$(echo ${File_row} | awk '{print $7}')
File_name=$(echo ${File_row} | awk '{print $9}')
Dir_File_Path=${DESTIN_PATH}/${monthnumber}/${File_Day}
Full_File_Path=${DESTIN_PATH}/${monthnumber}/${File_Day}/${monthnumber}-${File_Day}-$(basename ${File_name})
echo -n "Creating dir ${Dir_File_Path}: "
if mkdir -p ${Dir_File_Path} > /dev/null 2>&1
then
echo "OK"
else
echo "FAILED TO CREATE ${Dir_File_Path}!"
exit 1
fi
echo -n "Moving ${File_name} to ${Dir_File_Path}: "
if mv "${File_name}" "${Full_File_Path}" > /dev/null 2>&1
then
echo "OK"
else
echo "FAILED TO MOVE FILE. MOVING ON NEXT, IF ANY LEFT"
fi
done
}
### Main code
setvars
echo "Welcome to $0!"
check_args $@
build_file_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment