Script that returns all files that contain a specific string

I wrote the following to return all files in a folder which contain " - ".

use framework "Foundation"
use scripting additions

set sourceFolder to POSIX path of (choose folder)

getFiles(sourceFolder, " - ")

on getFiles(sourceFolder, theString)
	set fileManager to current application's NSFileManager's defaultManager()
	set theFolder to current application's |NSURL|'s fileURLWithPath:sourceFolder
	set folderContents to fileManager's contentsOfDirectoryAtURL:theFolder includingPropertiesForKeys:{} options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
	set thePred to current application's NSPredicate's predicateWithFormat_("(FSName CONTAINS[c] %@)", theString)
	set theFiles to folderContents's filteredArrayUsingPredicate:thePred
	return theFiles as list
end getFiles

The script returns the following error, apparently because the format of the predicate is not correct. I spent an hour or more online and with Shane’s book but couldn’t get the script to work. Thanks for the help.


Hi peavine.

The name of an item represented by an NSURL is its lastPathComponent. Similarly with a path represented by an NSString.

Thanks Nigel. That works great.