Midnight Commander multi-rename with numerical values for new file names
With F6 we can multi-rename group of selected files in mc. I know, for example, how to search and replace using some regexp tokens subset in this menu. But how to proceed if I need rename a group of files by adding a numeric counter to new filename? For example, given the selection:
a.sh
b.sh
c.shI want to rename files to:
01.sh
02.sh
03.shIs there some counter token?
1 Answer
There is no counter token to do that. But Midnight-Commander is too powerful to be so easily defeated! Create this new entry in your user menu (Command > Edit menu file > User or ~/.config/mc/menu):
x Rename with 00->99 counter preserving extension i=1 for file in %s; do extension=.${file##*.} [ "$extension" = ".$file" ] && extension="" cnt=$(printf '%%02d' "$i") mv -- "$file" "$cnt$extension" i=$((i+1)) doneThen select the files to be renamed, bring up the user menu with F2 and choose your new action with x.
Sample execution:
$ ls
a.sh b.sh c.sh 'h 10' 'zr.X&*!#@.f90'After selecting all the files and applying the action:
$ ls
01.sh 02.sh 03.sh 04 05.f90The shell script explained.
i=1
# %s expands to all selected files and we loop through each
for file in %s; do #This gets the extension of the file by removing everything up to the last dot extension=.${file##*.} #If the file had no extension, set extension to null [ "$extension" = ".$file" ] && extension="" #Format the counter appropriatedly, zero padding 1 to 9 #A double % is needed because MC interprets % especially, as noticed above with %s cnt=$(printf '%%02d' "$i") #Perform the renaming in a file, preserving extension (if existing) mv -- "$file" "$cnt$extension" i=$((i+1)) #Increment counter
done 3