Home > Software design >  Change the numerical sequence in filenames using bash/shell command
Change the numerical sequence in filenames using bash/shell command

Time:11-14

I have a group of files named in numerical sequence order from 1 to 1000,

s_nn_1.txt, s_nn_2.txt ..... s_nn_1000.txt .

I want to change the name of the file in a different sequence order as,

s_nn_1001.txt, s_nn_1002.txt .... s_nn_2000.txt .

I tried using two variables in 'for' loop but didn't work.

 for i in {1..1000}
do
for j in {1001..2000}
do
mv s_nn_"$i".txt s_nn_"$j".txt
done
done

Can you give any suggestions?

CodePudding user response:

In plain bash:

for ((i = 1; i <= 1000;   i)); do
    mv -i s_nn_$i.txt s_nn_$((i   1000)).txt
done

CodePudding user response:

While not an issue for OP's example, overlapping filenames should be considered when deciding on the order to perform the mv's.

If OP were going from {1..1000} to {500..1500}, half the files will be lost (eg, mv file1 file500 will overwrite the current file500, and later mv file500 file1000 will actually be making a copy of the original file1 and saving as file1000).

Generally speaking:

  • if increasing the numeric values then process the files in reverse numeric order
  • if decreasing the numeric values then process the files in (normal) numeric order

Applying this to OP's current code, and knowing the increase is 1000:

for i in {1000..1}
do
    mv s_nn_"$i".txt s_nn_"$((i 1000))".txt
done
  • Related