Skip to content

Instantly share code, notes, and snippets.

@hobroker
Last active December 12, 2021 15:05
Show Gist options
  • Save hobroker/7544d3b59e4646eb6b98fe4e335d0a0f to your computer and use it in GitHub Desktop.
Save hobroker/7544d3b59e4646eb6b98fe4e335d0a0f to your computer and use it in GitHub Desktop.
Group files in a directory by year
#!/usr/bin/env bash
#
# Usage: group.sh target_directory
# Result:
# target_directory/2020/...files from 2020
# target_directory/2021/...files from 2021
#
set -e
target="$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
# list files only, with the year
# example:
# 2020 image.jpg
# 2021 some_filename with space.jpg
files="$(ls -l --time-style=+%Y $target | grep '^-' | tr -s ' ' | cut -d " " -f 6- | awk NF)"
while IFS= read -r line; do
IFS=" " read year filename <<< "$line"
dir="$target/$year"
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