Is there a way to trim off the first 3 character of multiple file names? (or last 3 characters)


This code will do it for you:

set whichFile to choose file with multiple selections allowed
repeat with aFile in whichFile
    tell application "Finder"
        set filename to name of aFile
        set name of aFile to ((characters 4 thru -1 of filename) as string) --trim first 3
        --set name of whichFile to ((characters 1 thru -4 of filename) as string) --trim last 3
    end tell
end repeat

Note that stripping the last three will get rid of the extension. If that isn't what you want to happen, let me know in a comment.

| improve this answer | |
  • Oops, I started with the wrong property in there. Fixed; it should work now. – Nathan Greenstein Aug 4 '11 at 23:09
  • Sorry, I meant multiple file names. – daviesgeek Aug 4 '11 at 23:12
  • 1
    @daviesgeek Updated version above. – Nathan Greenstein Aug 4 '11 at 23:19
  • It doesn't exactly work. I have a bunch of files named test.txt, test copy.txt, test copy 2.txt, etc. When I ran your script, it clipped off the 3 characters in the middle i.e.: t copy.txt, t copy 2.txt. – daviesgeek Aug 4 '11 at 23:23
  • 1
    @daviesgeek It worked. Here's why: [tes]t copy.txt. If you remove the first three chars (in brackets), you get t copy.txt. It looks the same as if it clipped from the middle. Try it with a file called abcdefgh.txt. – Nathan Greenstein Aug 4 '11 at 23:26

Here's a shorter script:

tell application "Finder"
    repeat with f in (choose file with multiple selections allowed)
        set name of f to text 4 thru -1 of (get name of f)
    end repeat
end tell

Renaming files is often easier in the shell though:

for f in *; do mv "$f" "${f:3}"; done

Parameter expansion is documented in file:///usr/share/doc/bash/bashref.html#SEC30.

| improve this answer | |

Here is an Automator Workflow as a Service that will do what you want it to do.

All you have to do is load this workflow, and duplicate it to a Service and call the Service "Trim First 3" or something, then save it.

Then select a folder and select this service and it will take all files in the folder and trim the first 3 characters of the file name.

Good luck.

Trim First 3 Workflow (downloaded from my icloud account)

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .