Renaming files with number in file name in bash

I have many such files:

13831_1.jpg 13838_1.jpg 138035_1.jpg 138037_1.jpg 138039_1.jpg 

I need to add a value of 5,000,000 to file name numbers. The result should be as follows:

 5013831_1.jpg 5013838_1.jpg 5138035_1.jpg 5138037_1.jpg 5138039_1.jpg 

Is there a way to do this with bash or perl?

+6
source share
3 answers

Do: rename -v . If it outputs:

 Usage: rename [-v] [-n] [-f] perlexpr [filenames] 

This check is related to the fact that there are at least two different renaming tools with very different functions. And for the solution that I have, it needs a rename that perlexpr handles.

Then you can:

 rename 's/^(\d+)/5000000+$1/e' *.jpg 
+7
source

One way to do this is using only bash

 for file in *.jpg; do number=${file%_*} therest=${file#$number} mv "$file" "$((number+5000000))$therest" done 

Notes:

  • *.jpg will expand to a list of .jpg files in the current directory (ref: File name extension ).
  • ${file%_*} removes everything after _ in the file name and returns it. (ref: Enhancing shell options )
  • ${file#$number} removes the contents of the variable number from the very beginning of the file name and returns it. (ref: Enhancing shell options )
  • $((number+5000000)) evaluates the arithmetic expression inside and returns the result (ref: Arithmetic expansion )
+4
source
 $filename = "13831_1.jpg"; $org = explode("_".$filename); $addnumber = 5000000+$org[0]; $string = implode("_",$addnumber); 
-2
source

Source: https://habr.com/ru/post/947641/


All Articles