Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rename commands for migrating a macOS fileserver to Microsoft OneDrive
#! /usr/bin/env bash
# This is a small collection of helper commands for migrating a legacy macOS fileserver
# to OneDrive/Sharepoint. Filenames on cloud platforms are more restrictive than macOS, so
# a large number of files needed renaming before they could be synced to the Microsoft Cloud.
# 1. Use the rename CLI tool. It's installed by default on Debian/Ubuntu but needs to be
# installed on macOS and some other platforms. More here: http://plasmasturm.org/code/rename/
brew install rename
# 2. The following transformations should be performed in order. Some commands near the top
# are more refined versions of broader commands which appear later on, eg. slashed-dates
# before general slash replacement. It's not perfect, but works well enough to isolate
# extreme edge cases.
#
# These commands all use the `-n` "dry-run" flag to preview what will be changed
# To execute the command, change the flag to `-v` "verbose" or run with no flags
#
# Note: macOS invisibly remaps slashes to colons, a leftover of the MacOS 9 filesystems.
# Colons are otherwise forbidden in filenames on macOS, but POSIX needs to look for them
# Naive date fixes before removing the rest of the slashes
find . -depth -name '*:*' -execdir rename -n 's/(\d):(\d)/$1-$2/g' {} \;
# Replace all slashes in paths and filenames with an underscore
find . -depth -name '*:*' -execdir rename -n 's/:/_/g' {} \;
# Replace stars with bullets
find . -depth -name '*\**' -execdir rename -n 's/\*/•/g' {} \;
# Replace question marks
find . -depth -name '*\?*' -execdir rename -n 's/\?/_/g' {} \;
# Replace pipes
find . -depth -name '*\|*' -execdir rename -n 's/\|/_/g' {} \;
# Replace backslashes
find . -depth -name '*\\*' -execdir rename -n 's/\\/_/g' {} \;
# Remove trailing dots
find . -depth -name '?*.' -execdir rename -n 's/\.$//' {} \;
# Don't create dotfiles from bizarre extension-only filenames like " .png"
find -E . -depth -type f -regex '.*/ +\..*' -execdir rename -n 's/^\s+/_/' {} \;
# Replace leading spaces on directories with '- '
find -E . -depth -type d -regex '.*/ +.*' -execdir rename -n 's/^\s+/- /' {} \;
# Trim leading and trailing spaces
find -E . -depth -regex '.*/ +.*|.* +$' -execdir rename -n 's/^\s*(.*?)\s*$/$1/' {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment