0

I have 1000+ images and I have to rename them all so I was first testing my command on 20 images. They are named as

cropped1.jpg cropped2.jpg cropped3.jpg ... cropped20.jpg

I want to rename them as

21.jpg 22.jpg 23.jpg ... 40.jpg

So I was using this command

for i in {1..20}; do rename "s/"cropped"$i/$(expr $i + 20)/" * ; done

But my output is unexpected. Output is :

210.jpg  212.jpg  214.jpg  216.jpg  218.jpg  21.jpg   22.jpg  24.jpg  26.jpg  28.jpg 211.jpg  213.jpg  215.jpg  217.jpg  219.jpg  220.jpg  23.jpg  25.jpg  27.jpg  29.jpg

So where am I going wrong?

  • The first time time you use rename you should pass the parameter -n or long version -nono which prints the new names of the files to be renamed but doesn't actually rename them. This can prevent headaches down the road. – WinEunuuchs2Unix Mar 26 '18 at 21:00
  • That's a nice info and now I am more confused after seeing its output. Its output is saying '10.jpg' would be renamed to '210.jpg' and '10.jpg' would be renamed to '30.jpg' and same for files of 11 to 20. How is this one file being renamed two times? – Ujjwal Gupta Mar 26 '18 at 21:08
1

Don't mix shell and Perl code in rename command; it's all about Perl. Use this:

rename -n 's/cropped(\d+)/$1 + 20/e' cropped*.jpg

Remove -n switch when the output looks good.


If you insist to use your dirty way, don't use a glob * but the current file and modern shell :

for i in {1..20}; do
    test -s "cropped$i.jpg" && rename "s/cropped$i/$(($i + 20))/" "cropped$i.jpg"
done

I removed expr, it's outdated.


warning There are other tools with the same name which may or may not be able to do this, so be careful.

If you run the following command

$ file "$(readlink -f "$(type -p rename)")"

and you have a result that contains Perl script, ASCII text executable, and not containing ELF, then this seems to be the right tool =)

If not, to make it the default (usually already the case):

$ sudo update-alternatives --set rename /path/to/rename

Replace /path/to/rename with the path of your Perl rename executable.


If you don't have this command, search your package manager to install it or do it manually (no deps...)

| improve this answer | |
  • It gives me the right output. Thanks for that. But why command with -n is showing multiple lines for same file.It will be really helpful if you explain the changes you made, what they are doing in this command and what was wrong in mine? – Ujjwal Gupta Mar 26 '18 at 21:55
  • Answer of this question is in the first line of my answer – Gilles Quenot Mar 26 '18 at 22:02
  • @UjjwalGupta If it wasn't clear, it's because the glob matches every file for each loop in your command. – wjandrea Mar 26 '18 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.