Skip to content

Instantly share code, notes, and snippets.

@Abrifq
Created April 3, 2026 07:58
Show Gist options
  • Select an option

  • Save Abrifq/3616a9881309f484d007246f9c41ea42 to your computer and use it in GitHub Desktop.

Select an option

Save Abrifq/3616a9881309f484d007246f9c41ea42 to your computer and use it in GitHub Desktop.
Move files into folders according to their year and month, with a year limit
#!/bin/bash
# Usage: organize-by-year.sh "./Path with spaces"
# or: find . -type f -maxdepth 1 -exec organize-by-year.sh \"{}\" ";"
[ -z "$1" ] && echo "Usage: $0 \"some file\"" >&2 && exit 1
YEARFORMAT=+%Y # Get year only
MONTHFORMAT=+%m #Get month only
YEARMAX=2026 # Do not sort this year and after
FILEYEAR=$(ls -g --time-style=$YEARFORMAT "$1" | awk '{print $5}')
FILEMONTH=$( ls -g --time-style=$MONTHFORMAT "$1" | awk '{print $5}')
[ $FILEYEAR -ge $YEARMAX ] && { echo "Skipped file $1 as it's newer than the organizing limit. ($YEARFORMAT >= $YEARMAX)" >&2; exit 0;}
echo "Moving $1 to ${FILEYEAR}/${FILEMONTH} folder" >&2
mkdir -p "${FILEYEAR}"/"${FILEMONTH}";
mv "$1" "${FILEYEAR}"/"${FILEMONTH}";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment