Thursday, May 2, 2024
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 2125  / 2 Years ago, fri, december 3, 2021, 7:21:18

I have a situation where I have the following:



file01.ext
.
.
.
file99.ext
file100.ext
.
.
.


And I want to (using rename ) insert the '0' for the files 01-99 (so that they become 000-099) but not modify files larger than 100. Which expression should I use and what is a good source on learning regular expressions such as these?



On Windows I would have used Total Commander's multi rename function which has a very simple renaming syntax. Are there some good alternatives for that tool (multi-rename) for Ubuntu?


More From » command-line

 Answers
0

Using rename



A generally useful tool for this type of activity is rename from the perl package. It applies a perl substitution to the file name:



rename 's/file/file0/' file[0-9][0-9].ext


How this works:




  • s/file/file0/



    This is a perl substitution command. It replaces the occurrence of file in a file name with file0.


  • file[0-9][0-9].ext



    This is the list of files that rename is to operate on. [0-9] means any number from 0 to 9. [0-9][0-9] means any two numbers, one following the other.




The manpage for rename is here.



Note: This requires the perl version of rename. There is also a rename utility that is part of util-linux but it works differently.



Using bash



This approach uses a for loop combined with pattern substitution:



for f in file[0-9][0-9].ext; do mv "$f" "${f/file/file0}"; done


How it works:




  • for f in file[0-9][0-9].ext; do



    This starts a loop over each file name that matches the glob file[0-9][0-9].ext.


  • mv "$f" "${f/file/file0}"



    This renames the files using the bash's pattern substitution. It replaces file with file0` in the file name.


  • done



    This marks the end of the for loop.




This approach requires bash (or other advanced shell).



bash is the default interactive shell and this approach will work under bash. Thus, this should work on the usual command line.


[#22048] Saturday, December 4, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ttarum

Total Points: 417
Total Questions: 101
Total Answers: 115

Location: Maldives
Member since Wed, Nov 4, 2020
4 Years ago
ttarum questions
Sat, Aug 20, 22, 12:42, 2 Years ago
Wed, Sep 28, 22, 18:07, 2 Years ago
Mon, Feb 7, 22, 20:23, 2 Years ago
;