-3

I need to bulk rename files called plt????? to plt??????.

They're in numerical order from 0 to 99500 every 500, however I have some over 100,000 so I'd like them all to be in 6 figures.

Aim: current - plt99500 goal - plt099500

Any help would be appreciated

  • 1
    Hi. There's literally hundreds of questions on similar problems on here, so chances are you can piece together an answer by yourself! Could you explain what you've tried so far? What existing answers on this site have you looked into and where are you stuck? – Marcus Müller Oct 09 '23 at 10:23

2 Answers2

0

If we can assume that all your files are in the same directory, that none of the files can have the same name (e.g. you don't have plt500 and already have plt000500), all names consist of nothing but plt and then the number, and all files starting with plt need to be renamed, then you can do this:

for f in plt*; do
   numNoZero=$(sed 's/^0*//' <<<"${f/plt/}")
   echo mv -- "$f" "$(printf 'plt%06d' "$numNoZero")";
done

First, we iterate over all files and directories (letus know if you need to skip directories) whose name starts with plt, saving each as $f. Next, ${f/plt/} is the file name with the plt removed, so it should be just the number. We feed this through a sed command that removes any leading 0s, in case you have any, and save the result (the number without leading 0s) as $numNoZero. Next, we use printf, telling it t print plt and then the number, padded to 6 digits (%06d) and use this as the name we want to mv to.

If this looks right, remove the echo and re-run to actually rename the files.

Alternatively, if you have Perl rename (known as rename on Ubuntu and other Debian systems, perl-rename or prename in others), you can just do:

rename -n 's/plt0*(\d+?)$/sprintf("plt%06d", "$1")/e' plt*
terdon
  • 242,166
  • Thanks very much, I'd not come across the ${f/plt}, sed or %06d commands before but this worked great! – Gilly Russell Oct 09 '23 at 11:14
  • @GillyRussell you're welcome. See here for a reference on shell string manipulation tools, and here for a more general resource for string replacement. – terdon Oct 09 '23 at 11:15
0

Using Perl's rename (usable in any OS):

rename -n 's/\d+/sprintf "%06d", $&/e' ./plt[0-9]*

Remove -n switch, aka dry-run when your attempts are satisfactory to rename for real.