Saturday, October 21, 2017

#1 2017-08-07 03:18:12 pm

jbh
Member
Registered: 2017-04-05
Posts: 4

move a selected file and change its name

Using applescript I want to move a file that is selected in the Finder to another folder and also change the name of the file being moved.

This is what I’ve got so far.  It seems to work but also seems very clumsy.  Is there a better way of doing it please?

Applescript:


tell application "Finder"
   set itemlist to the selection
   set theFile to item 1 of itemlist
   set name of theFile to "zmoved.txt"
   set itemlist to the selection
   set theFile to item 1 of itemlist
   set thePath to desktop
   move theFile to desktop
end tell

Model: Macbook Pro
AppleScript: 2.5
Browser: Safari 603.2.5
Operating System: Mac OS X (10.11.6)


Filed under: rename file, move file

Offline

 

#2 2017-08-08 02:34:48 am

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 4412

Re: move a selected file and change its name

Hi. Welcome to MacScripter.

The problem you've found is that the Finder's references to folders and files are name references. When you change the name of the item referred to by 'theFile', the reference in the variable still has the old name, so you have to go back to the selection and get another reference with the new name.

One way round this is to coerce the original reference to an alias. This will keep track of the file after it's renamed or moved:

Applescript:


tell application "Finder"
   set itemlist to the selection
   set theFile to (item 1 of itemlist) as alias
   set name of theFile to "zmoved.txt"
   move theFile to desktop
end tell

Another possibility would be to move the file first. The Finder's 'move' command returns a reference to the item in the new location, so you could use that when renaming the file.

Applescript:


tell application "Finder"
   set itemlist to the selection
   set theFile to item 1 of itemlist
   set theFile to (move theFile to desktop)
   set name of theFile to "zmoved.txt"
end tell

Or you could use some combination of approaches, of course, depending on what else the script had to do. Any method will throw an error if an item with the same name already exists in the same folder at any stage.

Last edited by Nigel Garvey (2017-08-08 02:37:53 am)


NG

Offline

 

#3 2017-08-09 02:39:38 pm

jbh
Member
Registered: 2017-04-05
Posts: 4

Re: move a selected file and change its name

Thank you.  That not only tidies my script but also gives me two new insights. I'm beginning to understand the alias thing at last!

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)