I have folders of images with names like HolidaySnapsJune-1.tif , HolidaySnapsMay-12.tif and HolidaySnaps2018-005.tif
I want to add one leading 0 to the integer section of the filename if it is 2 digits long, and I want to add two leading 00s if it is just one digit long.
I would love to do this is a bash script which would recursively work on folders so it's important that the difference in names preceeding the '-' is ignored or worked-around.
I'm on Windows and just have access to whatever is built into git-bashso bash, sed, awk etc.
CodePudding user response:
You could use the rename.ul command from linux-utils.
rename [options] expression replacement file...
replaces the first occurence of expression by replacement in all names of files passed to the command.
Assuming your filenames contain exactly one hyphen -, you could simply run both of the following commands in a shell that supports the **/* glob syntax to recursively rename all files (Alternatively use find with the -exec option or something alike):
rename.ul -- - -00 **/*-?.tif
rename.ul -- - -0 **/*-??.tif
There are several options to rename.ul to prevent you from accidentally renaming inintended files (Watch out! The consequences could be quite drastic):
-v, --verbose
Show which files were renamed, if any.
-n, --no-act
Do not make any changes; add --verbose to see what would
be made.
-i, --interactive
Ask before overwriting existing files.
So you could either run the commands with the -nv options to perform a dry-run and see what changes the program would make, or add -i to be asked each time a file would be renamed.
CodePudding user response:
Using sed
$ printf '%s\n' $(ls *) | sed '/\.tif/s/\(.*-\)\(\<[0-9]\{2\}\>.*\)/\mv \1\2 \10\2/e;s/\(.*-\)\(\<[0-9]\>.*\)/mv \1\2 \100\2/e'
