Get results of Finder search as input using Applescript/shell script

I have created a workflow in Automator that uses a shell script to open a random file in a selected folder. What I really want to do is to be able to search across folders and open a random file using the search results as input.


My first thought was that there must be a way to do a search in finder and then get the contents of the active finder window (i.e. the search results) as input for my workflow, but everything I can find requires using a defined location as input.


Is there a way to accomplish what I want to do? It seems like it would be simple, but I know that's not always the case.

Posted on May 19, 2024 7:58 AM

Reply
Question marked as Top-ranking reply

Posted on May 20, 2024 3:32 AM

Here is an AppleScript that presents you with a single dialog where you enter the user-friendly Spotlight query (e.g. kind:pdf). The script then does:


  • Opens a Finder window with the results of that query and places the resulting files into a list before closing the Finder Window.
  • For lists of 50 items or less, it will use the AppleScript verb some to randomize the filename result.
  • For larger lists, it uses Apple's GamePlayKit randomizer for improved randomness and performance
  • The random file is then displayed as a selected item in a new Finder window where it can be opened with the appropriate application.


use framework "Foundation"
use framework "GameplayKit"
use AppleScript version "2.4"
use scripting additions

property ca : current application

try
	set query to text returned of (display dialog "Enter your Spotlight query: " default answer "")
	set result_code to (ca's NSWorkspace's sharedWorkspace)'s showSearchResultsForQueryString:query
	
	tell application "Finder"
		set query_files to (every item of its front window) as alias list
		close its front window
	end tell
	(count of query_files) > 0
on error
	return
end try
-- now random file of query results
if (count of query_files) ≤ 50 then
	set random_file to (some item of query_files) as text
else
	set random_file to my rand_selection(query_files) as text
end if
tell application "Finder" to reveal item random_file
set query_files to {}
return

on rdist(L, H)
	-- use Arc4 game randomizer instead of AppleScript's random which is more repetitive
	set randval to (ca's GKRandomDistribution's distributionWithLowestValue:L highestValue:H)'s nextInt()
	return randval as integer
end rdist

on rand_selection(alist)
	set file_ary to ca's NSMutableArray's array()
	file_ary's addObjectsFromArray:alist
	-- because Objective-C arrays are zero based and AppleScript lists are 1-based
	set rannbr to (my rdist(1, file_ary's |count|())) - 1
	set random_file to file_ary's objectAtIndex:rannbr
	-- clean up
	file_ary's removeAllObjects()
	return (random_file) as text
end rand_selection


Tested with up to 1000 PDF files from kind:pdf query on macOS Sonoma 14.5.

3 replies
Question marked as Top-ranking reply

May 20, 2024 3:32 AM in response to r00pea

Here is an AppleScript that presents you with a single dialog where you enter the user-friendly Spotlight query (e.g. kind:pdf). The script then does:


  • Opens a Finder window with the results of that query and places the resulting files into a list before closing the Finder Window.
  • For lists of 50 items or less, it will use the AppleScript verb some to randomize the filename result.
  • For larger lists, it uses Apple's GamePlayKit randomizer for improved randomness and performance
  • The random file is then displayed as a selected item in a new Finder window where it can be opened with the appropriate application.


use framework "Foundation"
use framework "GameplayKit"
use AppleScript version "2.4"
use scripting additions

property ca : current application

try
	set query to text returned of (display dialog "Enter your Spotlight query: " default answer "")
	set result_code to (ca's NSWorkspace's sharedWorkspace)'s showSearchResultsForQueryString:query
	
	tell application "Finder"
		set query_files to (every item of its front window) as alias list
		close its front window
	end tell
	(count of query_files) > 0
on error
	return
end try
-- now random file of query results
if (count of query_files) ≤ 50 then
	set random_file to (some item of query_files) as text
else
	set random_file to my rand_selection(query_files) as text
end if
tell application "Finder" to reveal item random_file
set query_files to {}
return

on rdist(L, H)
	-- use Arc4 game randomizer instead of AppleScript's random which is more repetitive
	set randval to (ca's GKRandomDistribution's distributionWithLowestValue:L highestValue:H)'s nextInt()
	return randval as integer
end rdist

on rand_selection(alist)
	set file_ary to ca's NSMutableArray's array()
	file_ary's addObjectsFromArray:alist
	-- because Objective-C arrays are zero based and AppleScript lists are 1-based
	set rannbr to (my rdist(1, file_ary's |count|())) - 1
	set random_file to file_ary's objectAtIndex:rannbr
	-- clean up
	file_ary's removeAllObjects()
	return (random_file) as text
end rand_selection


Tested with up to 1000 PDF files from kind:pdf query on macOS Sonoma 14.5.

May 19, 2024 10:09 AM in response to r00pea

AppleScript is good at scripting GUI apps, but not so good at various other tasks.


A shell script performing a file search would usually use either mdfind (Spotlight) or find to search for files based on paths and pattern matches.


The find command includes the ability to invoke one or more commands for each match, too.


https://stackoverflow.com/a/6043896


mdfind or grep would be used for searching file contents.


Some previous discussions:

May 19, 2024 9:38 PM in response to MrHoffman

Thank you for your response. I had a look at the links you provided, but doing the search in Finder is key so I can easily have the results in front of me and make changes on the fly, then execute my workflow using a keyboard shortcut. For my purposes, efficiency is not as important as simplicity for the user.


A dirty way I thought to accomplish what I want might be to select all files in the active Finder window (in this case, my search results); something like:


	tell application "Finder"
		activate
		select the entire contents of Finder window 1
	end tell



and then find some way to pass the selected files to (g)shuf to pick one file for me. Ideally I could get the files as a list without the need to actually select them all, but if that's what works I could always have the script select all > pass to shuf and open file > select none.


Or more simply, create a list of all the files showing in the active Finder window. Can this be done?


What do you think, am I barking up the right tree?

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Get results of Finder search as input using Applescript/shell script

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.