Tuesday, April 30, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 5469  / 1 Year ago, thu, may 4, 2023, 11:00:12

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?


More From » bash

 Answers
4

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

[#35566] Thursday, May 4, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jokaned

Total Points: 315
Total Questions: 116
Total Answers: 119

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;