This tiny script renames the files without moving them
n=0; for files in dir1/*.MOD dir2/*.MOD dir3/*.MOD; do printf -v new "${files/MOV*./%02d.}" "$((++n))"; echo mv -v "$files" "$new"; done
or more readably:
#!/bin/bash
n=0
for files in dir1/*.MOD dir2/*.MOD dir3/*.MOD; do
printf -v new "${files/MOV*./%02d.}" "$((++n))"
echo mv -v -- "$files" "$new"
done
Replace dir1
etc with the actual paths to your directories with the files
Remove echo
(it's just to test) after checking that this gives you what you want, to actually rename the files.
This numbers the files 01.MOD
, 02.MOD
, etc. If you have more than 99 files, replace %02d
with %03d
to get 001.MOD
etc
Explanation:
n=0
This just sets n
as 0
which is where I want bash to start counting from.
for files in dir1/*.MOD dir2/*.MOD dir3/*.MOD
A for
loop can execute commands iteratively on each file in turn. The syntax is for [variable] in [these things I want to do something to] ; do [command(s)] $[variable]; done
I have called the variable files
and found your files using a glob: *.MOD
is expanded by the shell to any file whose name ends in .MOD
(*
matches any characters)
printf -v new
printf
can format the new numbers with a fixed width for easier sorting. new
is another variable - this is the new name for the files.
"${files/MOV*./%02d.}" "$((++n))"
Referencing the variable files
from earlier and replacing MOV*
(remember *
is any character) with the result of the incrementing number $((++n))
(this is n
from the first line of the script, go up by one each time the loop is executed on a file) formatted using the code %02d
which to printf
means a decimal number of a fixed width of two digits 01, 02 etc. The search and replace pattern includes the .
to stop *
matching the whole filename and thus removing the extension.
echo mv -v -- "$files" "$new"
I add the echo
just for testing - this shows what will be done instead of actually doing it. Remove the echo when happy with the result to actually execute the command.
mv
renames or moves files; its syntax is mv oldname newname
. I added the -v
flag which tells mv
to be "verbose" and report each action. I added --
just to be safe - this tells mv
not to accept any further options, which stops any filenames starting with -
from being interpreted as options to the command - not needed in your case, but good practice.
Each file specified by the files
variable is mv
ed to a unique name created in the new
variable. We use $
to reference variables and these should be in "double quotes" to prevent the shell from doing any other expansions on the filenames - this stops special characters or spaces in filenames from causing problems.