Rename multiple files sequentially and starting by the same prefix
I have a folder containing like 1500 files, I want to rename them automatically via the terminal or a shell script as follows: "prefix_number.extension".
Example: cin_1.jpg, cin_2.png ...
Try:
count=0; for f in *; do [ -f "$f" ] && mv -i "$f" "cin_$((++count)).${f##*.}"; done
Or, if you prefer your commands spread over multiple lines:
count=0
for f in *
do
[ -f "$f" ] && mv -i "$f" "cin_$((++count)).${f##*.}"
done
How it works
-
count=0
This initializes the variable
count
to zero. -
for f in *; do
This starts a loop over all files in the current directory.
-
[ -f "$f" ] && mv -i "$f" "cin_$((++count)).${f##*.}"
[ -f "$f" ]
tests to see if the file$f
is a regular file (not a directory).If
$f
is a regular file, then the move (mv
) command is run.-i
tellsmv
not to overwrite any existing files without asking."cin_$((++count)).${f##*.}"
is the name of the new file.cin_
is the prefix.$((++count))
returns the value ofcount
after it has been incremented.${f##*.}
is the extension of file$f
. -
done
This marks the end of the loop.
Example
Consider a directory with these three files:
$ ls
alpha.jpg beta.png gamma.txt
Let's run our command:
$ count=0; for f in *; do [ -f "$f" ] && mv -i "$f" "cin_$((++count)).${f##*.}"; done
After running our command, the files in the directory now are:
$ ls
cin_1.jpg cin_2.png cin_3.txt
A rename
oneliner:
rename -n 's/.+\./our $i; sprintf("cin_%d.", 1+$i++)/e' *
This matches every file with a dot in its name (the last one, if multiple) and renames the part until the dot with cin_
followed by an incrementing number and a dot. With the -n
flag it just prints what it would do, remove it to perform the renaming.
Example run
$ ls
a.jpg b.jpg d.png e.png
$ rename -n 's/.+\./our $i; sprintf("cin_%d.", 1+$i++)/e' *
rename(a.jpg, cin_1.jpg)
rename(b.jpg, cin_2.jpg)
rename(d.png, cin_3.png)
rename(e.png, cin_4.png)
$ rename 's/.+\./our $i; sprintf("cin_%d.", 1+$i++)/e' *
$ ls
cin_1.jpg cin_2.jpg cin_3.png cin_4.png
Source: How to rename multiple files sequentially from command line?