Search code examples
bashrenamepuzzle

Massive rename of files but keep the same sorting


I have a lot of files in a folder with the same extension (e.g .vtk) and I am using a bash script to massive rename them with sequencial numbers. Here is the script i use:

n=0;
for file in *.vtk; do 
${file} 100_${n}.vtk;
n=$((n+1));
done

After the script's execution, all the files are rename like:

100_1.vtk
100_2.vtk
.
.
.

My problem is that I want to keep the sorting of files exactly the same as it was before. For example, if i had two sequential files named something.vtk and something_else.vtk, I want them after the renaming process, to correspond to 100_1.vtk and 100_2.vtk respectively.


Solution

  • Can you change your for loop from this:

     for file in *.vtk; do 
    

    to this:

     for file in $(ls -1 *.vtk | sort); do 
    

    If your filename don't contain spaces, this should work.