0

I made a lot of research before I put this question. I found a different links to do batch rename using regex like this and other similars:

*Pattern based, batch file rename in terminal

My problem is this, I want to do batch rename using Regex but my code doesn't work.

I have inside a folder different files named like this:

name_house_1_door.jpg
name_house_2_door.jpg
name_house_3_door.jpg
name_house_4_door.jpg

And I want to rename the files like this:

name_house_1.jpg
name_house_2.jpg
name_house_3.jpg
name_house_4.jpg

The code that approximate most of that I want was:

$  rename -v 's/house\_[0-9]\_door/house_[0-9]/'

But as you should know the first file was renamed as: name_house_[0-9].jpg

1

You need to use backreferences. Character classes don't mean anything in the replacement expression. In fact, few characters have special meanings in the replacement expression. I suppose something like:

rename -v 's/house_([0-9])_door/house_$1/'

(or)

rename -v 's/(house_[0-9])_door/$1/'

Also, do use the -n flag to see what renamings will happen before actually performing them.

3

A much easier way would be to just delete _door using rename:

rename -v 's/_door//' *

This searches for _door and replaces it with nothing, essentially deleting it.

2
  1. You are escaping the underscore in the search side of the expression and should not be.
  2. You need a sub-search (the numbers) and a place holder to store and use the result of the sub-search.

Adding parentheses around the [0-9] will create the needed sub-search. Since it is the first sub-search it can be referred to as $1 in the replace side. The result follows..

rename -v 's/house_([0-9])\_door/house_$1/' *

Hope this helps.

  • But you are also "escaping the underscore in the search side". This contradiction may confuse researchers. – mickmackusa Apr 17 '20 at 22:19
0

This works in Fish Shell

for file in *.jpg;  
    mv -n $file (basename $file _door.jpg).jpg; 
end

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.