Clancento
Clancento

Reputation: 47

Rename files using Regex on Mac Terminal

I'm trying to rename files in a folder which has files with a name like:

['A_LOT_OF_TEXT'].pdf&blobcol=urldata&blobtable=MungoBlobs

After install brew rename, I tried using this but it does not work:

rename -n -v  '.*?(.pdf)' *

I get the error:

Using expression: sub { use feature ':5.28'; .*?(.pdf) }
syntax error at (eval 2) line 1, near "; ."

Any solution to this?

Upvotes: 3

Views: 1633

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18631

You certainly want

rename -n -v  's/^(.*?\.pdf).*/$1/' *

See regex proof. Remove -n once you are sure the expression works for you well.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to $1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
    \.                       '.'
--------------------------------------------------------------------------------
    pdf                      'pdf'
--------------------------------------------------------------------------------
  )                        end of $1
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))

Upvotes: 4

trunc8
trunc8

Reputation: 21

I would advise you to look at the example usage in the manpage for rename.
One possible solution is as follows:

rename -v -n 's/(.*pdf).*/$1/' *

Explanation:

-v: print names of files successfully renamed
-n: dry run; don't actually rename
$1: First group in the matched regex
*: Run on all files in directory

Read more about the substitute command here.

Upvotes: 2

Related Questions