Skip to content

Instantly share code, notes, and snippets.

@knugie
Created June 28, 2013 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knugie/5885595 to your computer and use it in GitHub Desktop.
Save knugie/5885595 to your computer and use it in GitHub Desktop.
Rename all file in the current directory according to their file creation date For jpegs the file date will be set according to its EXIF data e.g. "20130628_014218.txt" not renamed "test.TXT" => "20130628_002938.txt" file extensions will be lower case
#!/usr/bin/env sh
# Rename all file in the current directory according to their file creation date
# For jpegs the file date will be set according to its EXIF data
# e.g.
# "20130628_014218.txt" not renamed
# "test.TXT" => "20130628_002938.txt"
# file extensions will be lower case
jhead -ft -dt -autorot -exonly -n%Y%m%d_%H%M%S *.[Jj][Pp][Gg]
find . -maxdepth 1 -type f -printf '%f\t%TY%Tm%Td_%TH%TM%TS\n' | awk '
BEGIN { _ord_init(); suf = "" }
function _ord_init( low, high, i, t) {
low = sprintf("%c", 7)
if (low == "\a") {
low = 0
high = 127
} else if (sprintf("%c", 128 + 7) == "\a") {
low = 128
high = 255
} else {
low = 0
high = 255
}
for (i = low; i <= high; i++) {
t = sprintf("%c", i)
_ord_[t] = i
}
}
function ord(str, c) {
c = substr(str, 1, 1)
return _ord_[c]
}
function chr(c) {
return sprintf("%c", c + 0)
}
{
a=$0;
split(a, arr, "\t")
old_name = arr[1]
ext = arr[1]
gsub(/^.*\./, "", ext)
sub(/\..*$/, "", arr[2])
new_name = arr[2]
if (old_name == new_name"."tolower(ext)) {
print "\""arr[1]"\" not renamed"
} else {
#print system("ls "old_name)
suf = ""
while (system("ls "sprintf("%s%s%s", new_name, suf,"."tolower(ext))" > /dev/null 2>&1") == 0) {
print sprintf("%s%s%s", new_name, suf,"."tolower(ext))" already exists"
last = substr(suf, length(suf), length(suf)+1)
if (last == "") {
suf = "a"
} else {
if(last == "z") {
suf = suf"a"
} else {
suf = substr(suf, 1, length(suf)-1)chr(ord(last) + 1)
}
}
}
new_name = sprintf("%s%s%s", new_name, suf,"."tolower(ext))
print "\""arr[1]"\" => \""new_name"\""
system("mv \""arr[1]"\" "new_name)
}
}'
@knugie
Copy link
Author

knugie commented Jan 1, 2016

Mac:

brew install jhead
brew install findutils --with-default-names

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment