Skip to content

Instantly share code, notes, and snippets.

@giannoug
Created August 11, 2021 19:26
Show Gist options
  • Select an option

  • Save giannoug/c8ffc0aadaa63904143717982b93ab12 to your computer and use it in GitHub Desktop.

Select an option

Save giannoug/c8ffc0aadaa63904143717982b93ab12 to your computer and use it in GitHub Desktop.

Revisions

  1. giannoug created this gist Aug 11, 2021.
    52 changes: 52 additions & 0 deletions rename.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    #!/usr/bin/env bash

    # Any copyright is dedicated to the Public Domain.
    # https://creativecommons.org/publicdomain/zero/1.0/

    # This script was used to migrate photos and videos saved
    # from Dropbox to OneDrive. Since both services use their
    # own naming scheme, I wanted to maintain consistency between
    # the newly uploaded files (automatically from my devices) and
    # the old ones migrated from Dropbox.
    # This script renames files from the Dropbox format
    # (e.g. 2018-07-27 20.12.21.jpg) to OneDrive format
    # (e.g. 20180727_201221.jpg). Special care was taken for duplicate
    # files within the same second (e.g: 2016-07-19 07.50.07-1.mp4 for
    # Dropbox and 20160719_075007_001.mp4 for OneDrive).

    source_dir=$1

    [ ! -d "$source_dir" ] && {
    echo "Source directory doesn't exist or isn't specified."
    exit 1
    }

    destination_dir=$2

    [ ! -d "$destination_dir" ] && mkdir "$destination_dir"

    for file in $source_dir/*; do
    basename=$(basename "$file")

    filename="${basename%.*}"
    extension="${basename##*.}"
    number=$(echo $filename | cut -d'-' -f4)

    # Replace . in filename to : so date parses the format
    replaced=${filename//\./\:}

    # Check if a sequence number is added at the end
    if [ -z "$number" ]; then
    new_date=$(date --date="$replaced" "+%Y%m%d_%H%M%S")
    new_filename=$destination_dir/$new_date.$extension
    else
    removed_number=${replaced%-*}
    new_date=$(date --date="$removed_number" "+%Y%m%d_%H%M%S")
    prepended_number=$(printf "%03d" $number)
    new_filename="$destination_dir/${new_date}_$prepended_number.$extension"
    fi

    cp -p "$file" $new_filename

    echo "Copied $file to $new_filename"
    done