2

I have a folder called P1. How can I make 59 copies of that folder but naming them incrementally, i.e., the new folders are named as P2,P3,...,P60?

Here's what I did, but it didn't work:
I made 59 copies manually and then tried to rename them using:

j=2;for f in /path/to/folders/*; do mv "$f" "$j"; let j=j+1; done

but instead all of my copied files including the original file were deleted from the directory.

What was wrong with the command I wrote and how I can do all the copying and renaming automatically?

Zanna
  • 70,465
Mahin Ra
  • 23
  • 2

1 Answers1

3

In your command, the directories are first renamed to the value of var j which is 2, so you end up with only one copy named 2 (as each overwrites the previous one). After that process has completed, j is reassigned to j+1 (echo $j returns 3) - it doesn't increment.

To make 59 copies you can do this:

for i in {2..60}; do cp -r -- P1 P"$i"; done

{2..60} expands to 2 3 4 5 6 7 all the way to 60

For fixed width numbers (so 02 comes before 11 when sorting) use printf:

for i in {2..60}; do cp -r -- P1 P$(printf %02d "$i"); done

This gives P02 P03 P04... P10, P11


For incremental renaming you might do something like this, assuming the copies aren't numbered...

j=0; for dir in /path/to/stuff/*; do mv -v -- "$dir" "$dir""$((++j))"; done

Fixed width format:

j=0; for dir in /path/to/stuff/*; do printf -v new "$dir%02d" "$((++j))"; mv -v -- "$dir" "$new"; done

Maybe worth making that last one more readable...

j=0
for dir in /where/my/stuff/is/*
  do printf -v new "$dir%02d" "$((++j))"
  mv -v -- "$dir" "$new"
done
Zanna
  • 70,465