Applescript - Recursively searching through directories - macos

I have a script that was generously created by another user here, but I've found that it doesn't read recursively through directories. The goal of the script is to read through all sub directories of a directory selected in the Finder, and to write out any absolute paths of files that are 255 characters or longer (path not filename). This is to find files with absolute path lengths that are too long on OSX for a Windows machine with the 255 character path limit, before transferring them from one to the other.
I've tried referencing this post to make it recursive but to no avail as the approach here appears quite different: AppleScript Processing Files in Folders recursively
on run
set longPaths to {}
tell application "Finder" to set theSel to selection
repeat with aFile in theSel
set aFile to aFile as string
set pathLength to count of characters in aFile
if pathLength > 255 then
set end of longPaths to aFile
end if
end repeat
if longPaths is not equal to {} then
-- do something with your list of long paths, write them to a text file or whatever you want
set pathToYourTextFile to (path to desktop folder as string)&"SampleTextFile.txt"
set tFile to open for access file (pathToYourTextFile as string) with write permission
repeat with filePath in longPaths
write (filePath & return as string) to tFile starting at eof
end repeat
close access tFile
end if
end run
Does anyone know the best way to add a recursive element to this script so that theSel includes all files in the subdirectories of the selected directory?

Here's a script which read recursively through directories:
property theOpenFile : missing value
tell application "Finder" to set theSel to selection
if theSel is not {} then
set pathToYourTextFile to (path to desktop folder as string) & "SampleTextFile2.txt"
set theOpenFile to open for access file (pathToYourTextFile as string) with write permission
repeat with aItem in theSel
tell application "Finder" to class of aItem is folder
if the result then my getFilesIn(aItem) -- aItem is a folder
end repeat
close access theOpenFile
end if
on getFilesIn(thisFolder)
tell application "Finder" to set theseFiles to files of thisFolder as alias list
repeat with thisFile in theseFiles
set f to thisFile as string
set pathLength to length of f
if pathLength > 255 then my writeToFile(f)
end repeat
tell application "Finder" to set theseSubFolders to folders of thisFolder
repeat with tSubF in theseSubFolders
my getFilesIn(tSubF) -- call this handler (recursively through this folder)
end repeat
end getFilesIn
on writeToFile(t)
write (t & return) to theOpenFile starting at eof
end writeToFile

Try:
tell application "Finder" to set theSel to every file in (get entire contents of selection)
Or something like that. Sorry, I am without a Mac to test the precise code. Whenever you ask for entire contents, you get everything in all subfolders of your chosen folder.

Related

how to fix 100's of alias' on mac after migration?

I really hope someone can help me out with this. I recently moved from one mac to another and did a clean install. I have several folders with hundreds of alias (how do you say the plural of alias?)...
The original file path is "/Volumes/Media Drive/Ableton/Warped Tracks/", and the new path needs to be "/users/joel/Music/Ableton Projects/Warped Tracks"
I see how to fix them one at a time, but that would take hours. I tried this applescript, but had no luck:
https://apple.stackexchange.com/questions/2656/how-do-i-fix-failed-aliases
Can anyone give me a better applescript or another solution? As I mentioned, I tried this applescript:
tell application "Finder"
set these_items to the selection
end tell
repeat with i from 1 to the count of these_items
set this_item to (item i of these_items) as alias
set this_info to info for this_item
if class of this_item is alias then
tell application "Finder"
set original_file to original item of this_item
set this_alias_file_name to displayed name of this_item
set container_folder to container of this_item
set the_path to the POSIX path of (original_file as alias)
set new_path to my replaceText("/Volumes/Media Drive/Ableton/Warped Tracks/", "/users/joel/Music/Ableton Projects/Warped Tracks", the_path)
move this_item to trash
try
make new alias file at container_folder to (POSIX file new_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- new original file not found, try relinking to old
try
make new alias file at container_folder to (POSIX file the_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- old original not found. link's dead Jim
display dialog "The original file for alias " & this_alias_file_name & " was not found."
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
end tell
end if
end repeat
on replaceText(find, replace, subject)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to find
set subject to text items of subject
set text item delimiters of AppleScript to replace
set subject to "" & subject
set text item delimiters of AppleScript to prevTIDs
return subject
end replaceText
Any help would be greatly appreciated.
Edit: I think the problem with the applescript for me is that I have folders further down the path that all are different, and THOSE each contain the individual alias files. IE:
"/users/joel/Music/Ableton Projects/Warped Tracks/Folder A/file.alias",/users/joel/Music/Ableton Projects/Warped Tracks/Folder B/file2.alias", etc, etc
I had same issue years ago (transfer between 2 media centers), and I made this program : it asks for folder were all broken alias are and then try to find again original path to rebuild them.
the thing is that any applescript instruction about alias gives error when link is broken, so you must use Finder info window to read original path without error when the link is already broken:
(this program assumes that original file name is unique)
-- Select main folder
tell application "Finder" to set Mon_Dossier to ((choose folder with prompt "Select top folder:" without invisibles) as alias) as string
-- repair alias in this folder and all subsequent folders (entire contents)
tell application "Finder" to set Mes_Alias to every file of entire contents of folder Mon_Dossier whose class is alias file
-- loop on each alias of the folder
repeat with Mon_Alias in Mes_Alias
-- found the original file path of Mon_Alias
-- try first with standard alias call
set F_Source to ""
try
tell application "Finder" to set F_Source to original item of Mon_Alias
end try
if F_Source is "" then
-- the link to original file is broken, then use on windows info method
set F_Source to Origine_Alias(Mon_Alias)
set F_Original to Decompose(F_Source)
-- no need to look original file as is, becuase the link is broken (path changed ?)
-- then directly search for the same file without extension
set Cible to ((chemin of F_Original) as string) & ((Nom of F_Original) as string)
tell application "Finder"
if exists file Cible then
-- file is found without extension
-- then delete alias and create new alias with same name and in same folder
set A_Nom to name of Mon_Alias
set A_Dossier to folder of Mon_Alias
delete Mon_Alias
set Nouvel_Alias to make alias to Cible at A_Dossier
set name of Nouvel_Alias to A_Nom
else
SLog("Alias=" & (Mon_Alias as string) & " File not found=" & Cible)
end if
end tell
else
-- the alias link is still valid : nothing to do ! go to next alias..
end if
end repeat
-- end main program
-- sub routine to find passe of broken link (original path/file can't be found)
-- the result is a unix path like folder/sub_folder/file
on Origine_Alias(F_Alias)
set R to ""
tell application "Finder" to open information window of file (F_Alias as text)
tell application "System Events" to tell process "Finder" to set R to value of static text 19 of scroll area 1 of front window
tell application "Finder" to close front window
return R
end Origine_Alias
-- sub routine to extract, from unix file path, the path, the file name and its extension: result is sent back in a record
-- Warning : we can't use "Posix file of" becuase the path and the file are non longer valid ! (then Posix gives error)
on Decompose(Local_F)
--search the first "." from right to find extension
set X to length of Local_F
repeat while (character X of Local_F is not ".") and (X > 0)
set X to X - 1
end repeat
if X > 0 then
set L_Ext to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X - 1) of Local_F
else
L_Ext = "" -- "." not found, then no extension !
end if
-- search first "/" from the right to extract file name
set X to length of Local_F
repeat while (character X of Local_F is not "/")
set X to X - 1
end repeat
set L_Nom to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X) of Local_F
try
set L_Chemin to POSIX file Local_F
end try
return {chemin:L_Chemin, Nom:L_Nom, Ext:L_Ext}
end Decompose
-- sub routine log (text log file on desktop)
on SLog(msg)
set the my_log to ¬
((path to desktop) as text) & "My_logfile.txt"
try
-- open file. create it if not yet exist
open for access file the my_log with write permission
-- add text at end of file
write (msg & return) to file the my_log starting at eof
close access file the my_log
on error
try
close access file the my_log
end try
end try
end SLog

AppleScript dead slow in moving files to folder

I'm trying to move a bunch of files into folders, based on the file creation date. Using the script below, the rate of move is about 1 file per second. 64000 files to go.
Script timed out when I tried
set myFiles to items of myFolder whose name ends with "jpg"
repeat with aFile in myFiles
So now I process file by file and only checking folder existing when the date comparison failed sped up the process only marginally. I've tried the obvious
set myDayBuddies to items of myFolder whose creation date is theFileDate
but this too, did not help really much. I suspect Finder reads the whole folder content time and time again, creating huge overhead.
What is the proper method of speeding up this any further? In PHP I know I can read entries from a directory stream, one by one.
Script:
tell application "Finder"
set myFolder to choose folder
set prevDateString to ""
repeat while true
try
set aFile to first item of myFolder whose name ends with "jpg"
set theFileDate to (the creation date of aFile)
set theDateString to my composedate(theFileDate)
if (theDateString is not prevDateString) then
if not (exists folder ((myFolder & theDateString) as text)) then
make new folder at myFolder with properties {name:theDateString}
end if
set prevDateString to theDateString
set destPath to (((myFolder as text) & theDateString) as alias)
end if
move aFile to destPath
on error
return
end try
end repeat
end tell
on composedate(aDate)
set y to (year of aDate as integer) as string
set m to (month of aDate as integer) as string
set d to (day of aDate as integer) as string
if length of m < 2 then
set m to "0" & m
end if
if length of d < 2 then
set d to "0" & d
end if
set myDateString to y & m & d
return myDateString
end composedate
System Events was created to take much of the load off the Finder. The Finder is slow so use system events when possible. I'm not sure how it will perform on a folder with 64000 files but give it a try.
set myFolder to choose folder
tell application "System Events"
set f to files of myFolder whose name extension is "jpg"
end tell
And if system events is still too slow then applescript alone isn't appropriate for such a large folder. You'll have to go to using the command line even though you said you don't want to. Something like this should be faster...
set myFolder to (choose folder) as text
set jpgFiles to paragraphs of (do shell script "ls " & quoted form of POSIX path of myFolder & " | grep 'jpg$'")
repeat with aFile in jpgFiles
set filePath to myFolder & aFile
tell application "System Events"
set theFileDate to creation date of file filePath
-- do more stuff
end tell
end repeat

Applescript - move files to folder which name begins with first 2 characters of filename

I'd like a little help fine tuning this script. Is it possible to have this script match subfolders based on the first two letters of file? Parent folder would be "Shots" which contains subfolders with unique two letter prefix "BA_Bikini_Atol" which contains subfolders within those folders for the specific shots ba_0020, ba_0030, etc. Would like to move a file, ba_0020_v0002 to the ba_0020 folder by selecting "shots" as the target and the script looks through all the sub folders for a match. Thoughts?
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
tell application "System Events"
set folderList to name of folders of mgDestFolder
set fileList to name of files of mgFilesFolder
end tell
repeat with i from 1 to (count folderList)
set folderName to item i of folderList
set filesToMove to {}
repeat with j from 1 to (count fileList)
set filename to item j of fileList
if filename begins with folderName then
set end of filesToMove to alias ((mgFilesFolder as string) & filename)
end if
end repeat
tell application "Finder"
move filesToMove to alias ((mgDestFolder as string) & folderName & ":")
end tell
end repeat
This works in my tests
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
(* get the files of the mgFilesFolder folder *)
tell application "Finder" to set fileList to files of mgFilesFolder
(* iterate over every file *)
repeat with i from 1 to number of items in fileList
set this_item to item i of fileList
set this_file_Name to name of this_item as string
(* get the file name code
Using the delimiter "_" break the name into fields of text and returning fields 1 thru 2 . i.e ba_0030 *)
set thisFileCode to (do shell script "echo " & quoted form of this_file_Name & " |cut -d _ -f 1-2")
log thisFileCode
tell application "Finder"
set folderList to ((folders of entire contents of mgDestFolder) whose name starts with thisFileCode)
if folderList is not {} then
move this_item to item 1 of folderList
end if
end tell
end repeat
FROM:
TO:
I've made (with the help from users of this site) the script you're referring to.
I've made similar (more efficient) scripts since then. Most of them depend on ASObjC Runner which you can get here: Download ASObjC Runner
If you have it installed I think the following script will work:
set mgFilesFolder to (choose folder with prompt "Where are the file stored which you would like to move?")
set mgDestFolder to (choose folder with prompt "Where are destination folders?")
tell application "ASObjC Runner"
set mgFiles to enumerate folder mgFilesFolder with recursion without including folders
repeat with mgFile in mgFiles
set mgPrefix to text 1 thru 7 of name of (about file mgFile include only "name")
set mgDest to enumerate folder mgDestFolder match prefix mgPrefix with recursion
manage file mgFile moving into mgDest
end repeat
end tell

Delete multiple files with applescript

Let’s say I have multiple files I want to delete, and they’re stored one per line in a files.txt file. I can delete them with
set deleteThis to paragraphs of (read "files.txt")
repeat with lineFromFile in deleteThis
set fileName to POSIX file lineFromFile
tell application "Finder" to delete file fileName
end repeat
This is the logic you usually find online — deleting them one by one, but not only does this screw your “Put Back” option (you have to ⌘z multiple times), it also plays the trash sound a bunch of times in a row.
Is there a way to delete multiple files at once, say via storing them in an array and deleting that?
Edit
The answer by #adayzdone is the best so far, but it fails on directories
Try:
set deleteThis to paragraphs of (read "files.txt" as «class utf8»)
set deleteList to {}
tell application "Finder"
repeat with aPath in deleteThis
try
set end of deleteList to (file aPath)
on error
try
set end of deleteList to (folder aPath)
end try
end try
end repeat
delete deleteList
end tell
Yes, Finder will take a list of paths as an argument to the delete command.
set deleteThis to paragraphs of (read "files.txt")
repeat with i from 1 to (count deleteThis)
set item i of deleteThis to POSIX file (item i of deleteThis)
end repeat
tell application "Finder"
delete deleteThis
end tell
Alternatively, if you're able to store the file paths as HFS paths instead of POSIX paths, you can skip the coercion:
set deleteThis to paragraphs of (read "files.txt")
tell application "Finder"
delete deleteThis
end tell
tell application "Finder"
set file_list to entire contents of (choose folder with prompt "Please select directory.")
move file_list to trash
end tell

Applescript - move files to folder which name begins with first 7 characters of filename

I've got 2 folders
the first folder contains all the files which I'd like to move to a subfolder of the second folder. I'd like to this based on the first 7 characters of both the file & folder names.
So if the first 7 characters of the subfolder in FOLDER 2 matches the first 7 characters of the file in FOLDER 1. The file get's moved into the subfolder of FOLDER 2
Right now I've got an Applescript which works, but it's terribly slow.
Here's the script so far:
set mgFileList to ""
set mgDestFolder to ""
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
set folderList to contents of mgDestFolder
tell application "Finder" to set fileList to files of mgFilesFolder
repeat with aFile in fileList
set prefix to getPrefix(name of aFile)
tell application "Finder"
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to destinationFolder
end try
end tell
end repeat
on getPrefix(aName)
set prefix to text 1 thru 7 of aName
return prefix
end getPrefix
I've only recently got into Applescripting. Can this be done more efficiently within Applescript? I've searched around for a solution which works with a shell script (which I think will probably be a lot faster), but haven't been able to get any of them working.
I'm working on OSX Mountain Lion 10.8.4
--
edit
I see that I've uploaded the wrong version of the script I've managed to put together so far. Above is the script that is working, but it's really slow. Probably because it doesn't use any shell script.
---------------update-------------------
Here is the final script that is working pretty fast right now:
set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?"
set mgDestFolder to choose folder with prompt "Where is the destination folder?"
tell application "System Events"
set fileList to files of mgFilesFolder whose name does not start with "."
repeat with aFile in fileList
set prefix to my getPrefix(name of aFile)
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to POSIX path of destinationFolder
end try
end repeat
end tell
on getPrefix(aName)
try
set prefix to text 1 thru 7 of aName
return prefix
on error
return aName
end try
end getPrefix
The Finder is generally a slow program because it does a lot of things on your computer. Therefore you should avoid using it if possible. In your case these tasks can be done using System Events. Try this, maybe it will be faster. Note that you had a couple mistakes in your code which are fixed in this code.
set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?"
set mgDestFolder to choose folder with prompt "Where is the destination folder?"
tell application "System Events"
set fileList to files of mgFilesFolder whose name does not start with "."
repeat with aFile in fileList
set prefix to my getPrefix(name of aFile)
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to POSIX path of destinationFolder
end try
end repeat
end tell
on getPrefix(aName)
try
set prefix to text 1 thru 7 of aName
return prefix
on error
return aName
end try
end getPrefix
Not sure how many files you're working with, but I tested this with 10 folders and ~100 files, and it took less than 4 seconds to run. Working with strings is much faster than working with files, so the script gets the files/folders as strings and builds aliases when they're needed.
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
--Always use System Events whenever possible. It's WAY faster than Finder.
tell application "System Events"
set folderList to name of folders of mgDestFolder
set fileList to name of files of mgFilesFolder
end tell
repeat with i from 1 to (count folderList)
set folderName to item i of folderList
set filesToMove to {}
repeat with j from 1 to (count fileList)
set filename to item j of fileList
if filename begins with folderName then
set end of filesToMove to alias ((mgFilesFolder as string) & filename)
end if
end repeat
--Can't use system events for moving files. You have to use Finder.
tell application "Finder"
move filesToMove to alias ((mgDestFolder as string) & folderName & ":")
end tell
end repeat
It might be easier to use shell scripting:
cd FOLDER1; for f in *; do d=../FOLDER2/"${f:0:7}"*; [[ -d $d ]] && mv "$f" "$d"; done

Resources