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?
rename
is a command-line tool that lets you rename files, using a Perl command to transform the name. A Perl command that's commonly used in this circumstance iss/REGEXP/REPLACEMENT/
.If I interpret your question correctly, you want to add a leading 0 in the names that have fewer than 4 digits, so that all the names end up having 4 digits. This slightly complicated expression handles the general case where you have file names with 1, 2 or 3 digits: it aligns all of them to 4 digits. The
e
modifier at the end causes the replacement to be interpreted not as a string but as a Perl expression. This expression repeats the digit0
as many times as necessary to pad the number to 4 digits.If the files you want to rename all have three digits, there are simpler ways, such as
or
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
: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 substringsA 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:With a recent version of bash you could write: