I mention that I've already checked similar questions about renaming files with bash script, but none has helped me with this problem.
I need to rename many files in a directory after the following rule: list the current files alphabetically, then replace their name with a given basic name, add a suffix which is the current file index and then add a given extension.
I encountered a problem at indexing the files. For instance, if I had 1000 files, after executing the script their names should be file0001.ext, file0002.ext ... file0010.ext ... file0099.ext ... file 0100.ext ... file0999.ext, file1000.ext
.
I've computed the needed number of zeros for every file, but I do not know how to implement the rule with a regular expression within the mv commnad. Below is my script code:
#!/bin/bash
nod=0
i=1
nof=$(ls -v $3 | wc -l)
cpy=$nof
while [ $cpy -gt 0]
do
nod=$((nod+1))
cpy=$((cpy/10))
done
for a in $(ls -v $3)
do
cpy_of_i=$i
i_digits=0
while [ $cpy_of_i -gt 0 ]
do
i_digits=$((i_digits+1))
cpy_of_i=$((cpy_of_i/10))
done
nr_zeros=$((nod-i_digits))
old=$3$a
new=$(echo $3$1[0]\*{nr_zeros}$i.$2)
mv $old $new
i=$((i+1))
done
Note: first argument is the new file name, the second argument is the new extension and the third argument is the directory which contains the files which are to be renamed. So the script will be called from command line with a command similar to this: ./rename.sh new_file pdf /home/dir/something/