I’m pretty new at this, but am trying to read a text file and extract a specific piece of information from the file (say, in the example below, the information on the line prefixed by SaveRGBImagesPrefix and ending at the return).
I know how to open a file, access it, and close it, but haven’t done much with reading and using delimiters (I’m guessing that’s what’s called for here…).
Is there a good generalized routine for reading a text file until a given phrase, and ending with a return?
Here’s an example of the contents of the text file:
If your text files aren’t large, this might work. It reads the entire file and then looks for the targeted text. If your files are large, you might need a script that reads the file in chunks. There is probably a more elegant way to do this but I haven’t had enough coffee to think about it.
set foo to read file "path:to:your:file"
set targetText to "SaveRGBImagesPrefix"
set extractedProperty to ""
set foundIt to "Target text not found."
set oldDelims to AppleScript's text item delimiters
try
set AppleScript's text item delimiters to {ASCII character 13}
set bar to text items of foo
repeat with thisItem in bar
if thisItem contains targetText then
set foundIt to thisItem
exit repeat
end if
end repeat
set AppleScript's text item delimiters to oldDelims
on error
set AppleScript's text item delimiters to oldDelims
end try
display dialog foundIt -- for demo only
repeat with thisWord in words of foundIt
if contents of thisWord is not targetText then
set extractedProperty to extractedProperty & thisWord & ":"
end if
end repeat
set extractedProperty to characters 1 thru -2 of extractedProperty as text
display dialog extractedProperty -- for demo only
set bar to read file "path:to:your:file" using delimiters {return}
In this way the file is automatically broken into a line-based list as it’s read. In the original code you have two copies of the entire file in memory - the original ‘pure’ copy, and the line-delimited version.
Of course you are correct. When I tried this earlier, it didn’t work, and then I got distracted. I later discovered that the test text file, generated with BBEdit, contained unix line breaks. Thanks for the heads up.