ap / rename

Rename multiple files
http://plasmasturm.org/code/rename/
Other
125 stars 11 forks source link

The transform -X not working #18

Closed il2020 closed 5 months ago

il2020 commented 5 months ago

I want to keep only numbers in the names of such files:

1. Stories Earl grey.jpg
14. PM Greenfield Royal Earl Grey.jpeg
15. PM Milky Ooolong.png
8. TB tess flirt.jpg

If I execute such a command, the extensions of files is removed:

% rename -n 's/(\d+).*/$1/' *     
'1. Stories Earl grey.jpg' would be renamed to '1'
'14. PM Greenfield Royal Earl Grey.jpeg' would be renamed to '14'
'15. PM Milky Ooolong.png' would be renamed to '15'
'8. TB tess flirt.jpg' would be renamed to '8'
%

That's why I want to add the transform -X. But in this case, there is no result at all:

% rename -n -X 's/(\d+).*/$1/' *
%
ap commented 5 months ago

You have to add an -e:

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

What’s going on is that if you don’t pass any switches that modify the filename (which -n doesn’t), rename guesses that you didn’t mean to do nothing, but rather you passed some code as the first argument. (This is for compatibility with the rename program that ships with perl, which doesn’t have any switches at all.) So your first command works.

In your second command, you added -X. This does process the filename, so now rename skips its guess and treats the first argument as a filename. Because of the -n, rename doesn’t touch the filesystem at all, so the fact that such a file does not exist doesn’t cause any errors. And since the only change you asked to be applied to each filename is -X, which by itself does nothing, rename prints nothing.

Adding the -e tells rename that the next argument is code you want to run at that point in the list of filename modification steps. You have to use -e whenever you want to give rename any more steps than one single code string. The usage message is split in two sections for this reason: switches (which don’t affect filenames (and where order doesn’t matter)) and transforms (which do (and it does)). Or just always use -e if you don’t want to have to think about it.