How to loop this TextEdit hyperlink script?

I am successfully using this script to extract hyperlinks from RTF text, however as I often haves folders with various documents I’d like to be able to choose the input folder, the destination folder and loop the script so it will process all documents in the folder.

this is the script which only works if I copy the file in my desktop


set filePath to (path to desktop folder as text) & "students.rtf"

set startDelimiter to "{HYPERLINK \""
set endDelimiter to "\"}}"
set linkDelimiter to "Read this message"

set rtfText to read file filePath
set text item delimiters to startDelimiter
set theItems to text items of rtfText
if (count of theItems) is greater than 1 then
	repeat with i from 2 to count of theItems
		set text item delimiters to endDelimiter
		set a to text items of (item i of theItems)
		set theLink to item 1 of a
		set text item delimiters to linkDelimiter
		set b to text items of (item i of theItems)
		set text item delimiters to theLink
		set (item i of theItems) to b as text
	end repeat
end if
set text item delimiters to startDelimiter
set adjustedText to theItems as text
set text item delimiters to ""
writeTo(adjustedText, filePath, false, string)



(*==================== SUBROUTINES ===================*)
on writeTo(this_data, target_file, append_data, mode) -- append_data is true or false, mode is string etc. (no quotes around either)
	try
		set target_file to target_file as text
		if target_file does not contain ":" then set target_file to POSIX file target_file as text
		set the open_target_file to open for access file target_file with write permission
		if append_data is false then set eof of the open_target_file to 0
		write this_data to the open_target_file starting at eof as mode
		close access the open_target_file
		return true
	on error
		try
			close access file open_target_file
		end try
		return false
	end try
end writeTo

Thanks for the kind help

You could add the “choose folder” selection option:

Replace the line


set filePath to (path to desktop folder as text) & "students.rtf"

with something like this:

you may have to tweak it a bit to fit your variables.


property extension_list : {"rtf""}

tell application "Finder"
try
set the source_folder to choose folder with prompt ¬
"Pick a folder containing the images to process:"
set these_files to every file of the source_folder whose name extension is in the extension_list
repeat with i from 1 to the count of these_files
set this_path to (item i of these_files) as string
set this_file to choose file
set theFolder to choose folder with prompt "Select anything for this example"

set filePath to this_path & this_file
-- your script

end repeat
end try