Ubuntu – How to rename files with count

bashbatch-renamerename

I have a directory like this:

randomized_quad015.png
randomized_quad030.png
randomized_quad045.png
randomized_quad060.png
randomized_quad075.png
randomized_quad090.png
randomized_quad1005.png
randomized_quad1020.png
randomized_quad1035.png
randomized_quad1050.png
randomized_quad105.png
randomized_quad1065.png
randomized_quad1080.png
randomized_quad1095.png
randomized_quad1110.png
randomized_quad1125.png
randomized_quad1140.png

and I want to rename the first files adding 0 in front of number, like:

randomized_quad0015.png

But I don't know how. Some help?

Best Answer

As an alternative to the various Perl-based methods in other answers, you can do this particular example, and lots of other similar ones with plain bash:

for i in randomized_quad???.png; do   
  mv $i randomized_quad0${i#randomized_quad}
done

This loops over the filenames with only three characters in the number region, and the variable expression in braces takes each filename, snips "randomized_quad" off the front (with the # operator), and adds "randomized_quad0" on the front.

Other excitingly useful operators like this include:

  • % - cut something off the end
  • / - search and replace (/ for the first match, // for all matches)
  • : - for extracting substrings

A more complete list with examples is here. Also, note that these use POSIX-style regular expressions, so . will match any character, not just a "." If you want to match a ".", you should 'escape' it, with a backslash:

TestVariable1="filename.png"
TestVariable2="filename0png"

echo "${TestVariable1%.png}"
> filename

echo "${TestVariable2%.png}"
> filename

echo "${TestVariable1%\.png}"
> filename

echo "${TestVariable2%\.png}"
> filename0png
Related Question