Thursday, December 14, 2017

#1 2005-10-12 06:59:15 am

julifos
Administrator
From:: Malasaña, Madrid
Registered: 2002-11-20
Posts: 2014

How do I rename a file, or a group of files?

The first thing to remember is that it is the Finder is the application that handles the naming of files. Suppose you have a file called "Monterey" on your desktop and you want to rename it "Eden" via AppleScript. The following would give you an error:

Applescript:

set the name of file "Monterey" to "Eden"

This is because setting a file name is a Finder task. Putting the same line inside a Finder tell-block fixes the problem:

Applescript:

tell application "Finder"
   set the name of file "Monterey" to "Eden"
end tell

Another example: using AppleScript's Text Item Delimiters you could rename a file with any extension (.tif, .tiff, .psd, etc) to its corresponding .jpg filename using an approach like this:

Applescript:

tell application "Finder"
   set theFile to file "Disneyland.tiff"
   
   set oldDelims to AppleScript's text item delimiters
   set AppleScript's text item delimiters to {"."}
   
   try
       set fileName to name of theFile --> Disneyland.tiff
       set nameWithoutExtension to first text item of fileName --> Disneyland
       set newName to nameWithoutExtension & ".jpg " --> Disneyland.jpg
       set name of theFile to newName --> rename the file
       set AppleScript's text item delimiters to oldDelims
   on error
       set AppleScript's text item delimiters to oldDelims
   end try
end tell

You could use a repeat loop to rename a folder of files in this way. Always remember to put the naming of files in a Finder tell-block!

For more advanced file-renaming routines, you may consider learn a bit of shell scripting and use of the do shell script command, which is fastest than the Finder.


Filed under: Finder

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)