Delete Part of File Names

I would like to rename a bunch of files leaving only the first three characters + a fixed extension (EXT).

For example:
Originale file names: bkr-hhdjj2.jpg, alp-jhhf45.jpg
New file names: bkr_EXT.jpg, alp_EXT.jpg

I know how to do basic renaming using the "Move or rename file" action and variables, but I'm unsure how to tell it leave the first three characters. Can anyone help me?

Thanks in advance.

You need a macro that supports regular expressions for file renaming. See Rename Files Mystery for a couple alternatives.

Then you need a regular expression to plug in to it:

Search for : ^(.{3}).+?.
Replace with: $1_EXT.

That gets you:

  • bkr-hhdjj2.jpg >> bkr_EXT.jpg
  • alp-jhhf45.jpg >> alp_EXT.jpg

I made a macro that almost works. I get the following result:

  • bkr-hhdjj2.jpg >> bkr_EXThhdjj2.jpg
  • alp-jhhf45.jpg >> alp_EXTjhhf45.jpg

So it looks like I need to change something in the expression to remove the last part of the original file name?

Rename (keep first three characters).kmmacros (2.8 KB)

I ended up solving it myself :slight_smile:

Search for : (^.{0,3})(.+)
Replace with: \1_EXT.jpg

This did the trick.

Just to clarify the differences:

  • The $1 and \1 are equivalent (but both aren't always supported).

  • ^ starts at the beginning of the search string. There's no need to capture it in parentheses

  • . means any character.

  • {3} means exactly three while {0,3} means zero up to three. You're looking for exactly three.

  • .+?. means anything up to a period while (._) means capture everything else. No need to capture all that (parentheses) and no need to go through the extension.

So, yes, your regex works but it's doing extra work and is less precise than the one I suggested. The one I suggested will fail if there's a period in the filename before the one for the extension, otherwise it's insignificantly more efficient.

Ain't regexing fun?

2 Likes

I'm absolutely sure you're are right. All I know is that what ever I did works. :wink:

And of course a KM Get Substring action with get you there directly:

e.g.


from:

New filename derived with Get Substring action.kmmacros (21.1 KB)

1 Like