Chrys
Chrys

Reputation: 313

How to rename files with sequential numbers with bash?

I have 308,000 files located in the same directory, which are named using important information I would like to keep:

e.g.

"f_500_0.1_0.005_150_25.gen"
"f_500_0.1_0.005_150_26.gen"
"f_500_0.1_0.005_150_27.gen"
 [...]
"f_1000_0.1_0.005_150_25.gen"
"f_1000_0.1_0.005_150_26.gen"
"f_1000_0.1_0.005_150_27.gen"

I would like to rename all these files just by adding a number at the beginning of each filename, which will go from 1 to 12 sequentially until all 308,000 files have been assigned a number, like this:

# First 12 files:
"1_f_500_0.1_0.005_150_25.gen"
"2_f_500_0.1_0.005_150_26.gen"
[...]
"10_f_500_0.1_0.005_150_27.gen"
"11_f_500_0.1_0.005_150_28.gen"
"12_f_500_0.1_0.005_150_29.gen" 
# (and then again from 1 to 12 for the next 12 files:)  
"1_f_1000_0.1_0.005_150_25.gen"
"2_f_1000_0.1_0.005_150_26.gen"
[...]
"10_f_1000_0.1_0.005_150_27.gen"
"11_f_1000_0.1_0.005_150_28.gen"
"12_f_1000_0.1_0.005_150_29.gen" 
 # (and so on until all 308,000 files are renamed)

In the end, I just want to have grossly as many files with filename starting by "1_f...", than files with filename starting with "2_f..", and so on. How could I do that within my Unix shell? I am not fluent with bash.

Thanks a lot!

Upvotes: 0

Views: 3676

Answers (1)

udiboy1209
udiboy1209

Reputation: 1502

This is fairly simple with a for loop in bash.

You can loop over all files in the directory by using output of ls command to for command. You need a variable which stores the index and you can update it in the loop.

export i=1
for f in $(ls)
do
   # Copy file to new location, safer than move in case you make a mistake
   cp $f ../new_directory/$i"_"$f -v

   # Increment
   let i=i+1
   # Reset if exceeds 12
   if [ $i -gt 12 ]
   then
      export i=1
   fi
done

You will have to be in the files directory, and will have to create new_directory. Best way to run is to save this as a script, and execute.

Upvotes: 1

Related Questions