Skip to content

Instantly share code, notes, and snippets.

@realeroberto
Created November 4, 2014 11:55
Show Gist options
  • Save realeroberto/86814193428f11601470 to your computer and use it in GitHub Desktop.
Save realeroberto/86814193428f11601470 to your computer and use it in GitHub Desktop.
Rename a bunch of files with embedded dates as ISO 8601 dates.
#
# rename a bunch of files as follows
#
# DDMONYYYY_NAME.EXT ==> YYYY-MM-DD_NAME.EXT
#
# i.e. it changes the date to ISO 8601 form
#
# for each file in the local path
Get-ChildItem -name |% {
# old filename is in the form DDMONYYYY_NAME.EXT (e.g. 26APR1982_foobar.txt)
$old_filename = $_;
# extract the date part (e.g., 26APR1982)
$old_date_string = $($old_filename.Substring(0, 9));
# extract the suffix part (e.g.. foobar.txt);
$filename_suffix = $_.Substring(10);
# convert the date part to a date object
$date = [datetime]::Parse($old_date_string);
# represent the date object as a ISO 8601 date (e.g., 1982-04-26)
$new_date_string = $date.ToString("yyyy-MM-dd");
# build up the new filename (e.g. 1982-04-26_foobar.txt)
$new_filename = [string]::join("_", ($new_date_string, $filename_suffix));
# rename the file
move $old_filename $new_filename;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment