Skip to content

Instantly share code, notes, and snippets.

@hobroker
Created December 13, 2021 21:25
Show Gist options
  • Save hobroker/a41b1ea9520a9caf9345211fc3d901ff to your computer and use it in GitHub Desktop.
Save hobroker/a41b1ea9520a9caf9345211fc3d901ff to your computer and use it in GitHub Desktop.
Group files in a year each x months (default 4)
#!/usr/bin/env bash
#
# Usage: group.sh target_directory 4
# Result:
# target_directory/part1of3/...files from January till April (inclusive)
# target_directory/part2of3/...files from May till August
# target_directory/part3of3/...files from September till December
#
set -e
target="$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
each=${2:-'4'}
parts=$((12 / each))
# list files only, with the year
# example:
# 01 image.jpg
# 02 some_filename with space.jpg
files="$(ls -l --time-style=+%m $target | grep '^-' | tr -s ' ' | cut -d " " -f 6- | awk NF)"
while IFS= read -r line; do
IFS=" " read month filename <<< "$line"
# remove leading 0
month=$(echo $month | sed 's/^0*//')
part=$(((month + each - 1)/each))
part="part${part}of$parts"
dir="$target/$part"
file="$target/$filename"
printf "%s <- %s" $dir $file
mkdir -p "$dir"
mv "$file" "$dir"
printf " $\n"
done <<< "$files"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment