I am currently using this Applescript I found that searches for a file name and returns the file path in a text doc. This works fine for finding 1 or 2 files, but I would like to find 500 files that are spread over hundreds of folders. My ideal script would use data from an excel spreadsheet or csv, perform a search, find the file and make a copy of it in a designated folder on my desktop. Any help is appreciated.
Here is the script I found:
tell application "System Events"
activate
set thePattern to text returned of (display dialog "Search for" default answer "")
end tell
if thePattern = "" then return
try
set foundFiles to do shell script "mdfind -name " & quoted form of thePattern & " | /usr/bin/egrep -i " & quoted form of thePattern & "[^/]*/?$ | /usr/bin/grep -vi " & quoted form of thePattern & ".*" & quoted form of thePattern
on error
set foundFiles to "Nothing Returned"
end try
if foundFiles = "" then set foundFiles to "Nothing Returned"
tell application "TextEdit"
activate
delay 0.5
try
set theDoc to document 1
get text of theDoc
if result is not "" then
make new document
set theDoc to result
end if
on error
make new document
set theDoc to result
end try
set text of theDoc to foundFiles
end tell
You need to read the data from the text file, then turn it into a return or linefeed delimited list and do a repeat over the items of this list. Then turn each item (which is actually a line) into e.g. a tab delimited list and again do a (nested) repeat loop over the items of this list. If you know that e.g. item 3 is the file path, you can set a variable to item 3 of the line as text and use this variable in your shell script.
I think you need to show that you understand the concept of repeat loops by posting your own attempt of implementing this. If you do, I'll be happy to come back and help you with the next step.
Kind regards,
Mark
Related
I have been exploring coding recently and I really enjoy grinding a problem down. I am getting comfortable with AppleScript now and I think it is a good option for what I want to do in the future with coding. My gut tells me that Automator would be less efficient RAM wise and I don't like how it is sectioned off; to constraining and confusing. I like the sandbox feature of a scripting language. I built a pretty good script for a web crawler that opens an online stock portfolio and prunes the market price of cryptocurrencies. I plan on utilizing technological decision making labs to create a cryptocurrency forecasting workbook for my hopes and dreams to make money some day, if ever :[ I have day dreams of making a live excel file that builds plots with hourly fluctuations in the trading.
To make it a full fledged automated system I need some sort of way to loop the script or schedule it to run on a schedule to get lots of data points for the mathematical models I hope to formulate from the data. I have tried really hard to make the idle handler work but it just doesn't operate like the tutorials describe. It seems you can't use "on idle" with certain commands and I get an error every gosh darn time I use the thing. I found a help page that showed how to incorporate a "beep" function to make sure the idle loop is running and when I compile and save as an "always running App" it doesn't play the beep so I guess that's another problem I haven't figured out. I get the beep to work sometimes but with my final draft of my program now I can't get it to work. I have tried inserting it ever so carefully within tell statements because I have found it works with them sometimes. And I guess you can't have the idle handler span the entire script; it needs to be called in one command structures tree to work. But I still haven't had the App run the script from idle with all the work I've put in looking into this solution. Anybody that has the hush hush on the idle handler secrets can do their best to try to explain the inner workings of the script to me but I find that it takes me a long time to learn coding because it is a lot of very technical reading with precious few opportunities to forge your own learning. Coding is a lot of boiler plate rehashes and I assume I will be chipping away at writing code long into my grey hair days with what I've learned so far.
But if you could use this question to collect some reading material on how to take a moderately well written script to run in 30 minute increments in the background of a laptop that can handle most computing loads fairly well it would be most appreciated. I'm not against Automator; it's just hard in it's own right with all the things you have to know to get it to work. As I said, any info about the idle handler and how to get it to work would be helpful. Also, if it is possible to write code in AppleScript to generate plots in Microsoft Excel, I like making models for shirts and googles.
I guess I will share what I've worked on for the last chunk of a weeks worth of grinding the tutorials offered currently online for free. Any critiques or suggestions on how to make the script I've got so far better is greatly appreciated and I don't mind if you snatch something you like if I did a good jerb. This is a web crawling cryptocurrency stock analyzer currently. It follows 3 currencies and writes data to an excel file with year, month, day, and seconds to collect a mass of data for a stronger mathematical model. I studied technological forecasting techniques that apply seasonality to data so the forecasts are better than just using the trend line function in excel, though with the variability with cryptocurrency I wouldn't put much salt on a long term prediction of market prices. I just want to be watching for those oh so gut wrenching stock crashes for a chance to limp in to the game with what little money I can scrounge together for sustenance.
--Boiler plate code to manipulate the HTML to let us pull the market price of the stock.--
--3 sets of modifiers for the 3 stocks--
to extractTextBitcoin(searchTextBitcoin, startTextBitcoin, endTextBitcoin)
set tid to AppleScript's text item delimiters
set startTextBitcoin to ">"
set searchTextBitcoin to {"priceValue___11gHJ", 0 & searchTextBitcoin}
set AppleScript's text item delimiters to startTextBitcoin
set endItemsBitcoin to text item -1 of searchTextBitcoin
set AppleScript's text item delimiters to endTextBitcoin
set beginningToEndBitcoin to text item 1 of endItemsBitcoin
set AppleScript's text item delimiters to startTextBitcoin
set endTextBitcoin to (text items 2 thru -1 of beginningToEndBitcoin) as record
set AppleScript's text item delimiters to tid
end extractTextBitcoin
to extractTextLitecoin(searchTextLitecoin, startTextLitecoin, endTextLitecoin)
set tid to AppleScript's text item delimiters
set startTextLitecoin to ">"
set searchTextLitecoin to {"priceValue___11gHJ", 0 & searchTextLitecoin}
set AppleScript's text item delimiters to startTextLitecoin
set endItemsLitecoin to text item -1 of searchTextLitecoin
set AppleScript's text item delimiters to endTextLitecoin
set beginningToEndLitecoin to text item 1 of endItemsLitecoin
set AppleScript's text item delimiters to startTextLitecoin
set endTextLitecoin to (text items 2 thru -1 of beginningToEndLitecoin) as record
set AppleScript's text item delimiters to tid
end extractTextLitecoin
to extractTextDogecoin(searchTextDogecoin, startTextDogecoin, endTextDogeecoin)
set tid to AppleScript's text item delimiters
set startTextDogecoin to ">"
set searchTextDogecoin to {"priceValue___11gHJ", 0 & searchTextDogecoin}
set AppleScript's text item delimiters to startTextDogecoin
set endItemsDogecoin to text item -2 of searchTextDogecoin
set AppleScript's text item delimiters to endTextDogeecoin
set beginningToEndDogecoin to text item 1 of endItemsDogecoin
set AppleScript's text item delimiters to startTextDogecoin
set endTextDogeecoin to (text items 2 thru -1 of beginningToEndDogecoin) as record
set AppleScript's text item delimiters to tid
end extractTextDogecoin
--A tell statement to open the webpage where the stocks are measured--
tell application "Safari"
activate
do shell script "open https://coinmarketcap.com/currencies/bitcoin/"
end tell
delay 2
--A function that differentiates the data on the web page by class and number. It
--also uses JavaScript to write the data to a useable format.
to getInputByClassBitcoin(theClass, num)
tell application "Safari"
set input to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return input
end getInputByClassBitcoin
--The function with the class and number criteria manually pulled from the web page--
getInputByClassBitcoin("priceValue___11gHJ", 0)
--Setting the instataneous stock price to a variable to input in Excel--
set BitcoinPrice to getInputByClassBitcoin("priceValue___11gHJ", 0)
on FinalFuction(BitcoinPrice)
set FinalFuction to extractTextBitcoin(BitcoinPrice, "<div class=>", "</div>")
return FinalFuction(BitcoinPrice)
end FinalFuction
tell application "Safari"
activate
do shell script "open https://coinmarketcap.com/currencies/litecoin/"
end tell
delay 2
to getInputByClassLitecoin(theClass, num)
tell application "Safari"
set token to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return token
end getInputByClassLitecoin
getInputByClassLitecoin("priceValue___11gHJ", 0)
set LitecoinPrice to getInputByClassLitecoin("priceValue___11gHJ", 0)
on ReturnFuction(LitecoinPrice)
set ReturnFuction to extractTextLitecoin(LitecoinPrice, "<div class=>", "</div>")
return ReturnFuction(LitecoinPrice)
end ReturnFuction
tell application "Safari"
activate
do shell script "open https://coinmarketcap.com/currencies/dogecoin/"
end tell
delay 2
to getInputByClassDogecoin(theClass, num)
tell application "Safari"
set blast to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return blast
end getInputByClassDogecoin
getInputByClassDogecoin("priceValue___11gHJ", 0)
set DogecoinPrice to getInputByClassDogecoin("priceValue___11gHJ", 0)
on EndFuction(DogecoinPrice)
set EndFuction to extractTextDogecoin(DogecoinPrice, "<div class=>", "</div>")
return EndFuction(DogecoinPrice)
end EndFuction
--Opens the compiled Excel workbook, negates user input, finds the next available--
--cell to input data, and fills the fields with Year, Month, Day, Time, and Price--
tell application "Microsoft Excel"
open "/Users/clusterflux/Desktop/ㅇㅅㅇBITCOINㅇㅅㅇ.xlsx"
set display alerts to false
delete active sheet
first row index of (get end (last cell of column 9) direction toward the top)
set LastRow to first row index of (get end (last cell of column 9) direction toward the top)
--write date and time for each market reading to excel file
set value of cell ("I" & LastRow + 1) to "=YEAR(TODAY())"
set value of cell ("J" & LastRow + 1) to "=MONTH(TODAY())"
set value of cell ("K" & LastRow + 1) to "=DAY(TODAY())"
set value of cell ("L" & LastRow + 1) to (time string of (current date))
set value of cell ("M" & LastRow + 1) to BitcoinPrice
set workbookName to ("ㅇㅅㅇBITCOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
save active workbook in destinationPath
end tell
tell application "Microsoft Excel"
open "/Users/clusterflux/Desktop/ㅇㅅㅇLITECOINㅇㅅㅇ.xlsx"
set display alerts to false
delete active sheet
first row index of (get end (last cell of column 5) direction toward the top)
set LastRow to first row index of (get end (last cell of column 5) direction toward the top)
set value of cell ("C" & LastRow + 1) to "=YEAR(TODAY())"
set value of cell ("D" & LastRow + 1) to "=MONTH(TODAY())"
set value of cell ("E" & LastRow + 1) to "=DAY(TODAY())"
set value of cell ("F" & LastRow + 1) to (time string of (current date))
set value of cell ("G" & LastRow + 1) to LitecoinPrice
set workbookName to ("ㅇㅅㅇLITECOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
save active workbook in destinationPath
end tell
on idle
return 3
beep
tell application "Microsoft Excel"
open "/Users/clusterflux/Desktop/ㅇㅅㅇDOGECOINㅇㅅㅇ.xlsx"
set display alerts to false
delete active sheet
first row index of (get end (last cell of column 5) direction toward the top)
set LastRow to first row index of (get end (last cell of column 5) direction toward the top)
set value of cell ("C" & LastRow + 1) to "=YEAR(TODAY())"
set value of cell ("D" & LastRow + 1) to "=MONTH(TODAY())"
set value of cell ("E" & LastRow + 1) to "=DAY(TODAY())"
set value of cell ("F" & LastRow + 1) to (time string of (current date))
set value of cell ("G" & LastRow + 1) to DogecoinPrice
set workbookName to ("ㅇㅅㅇDOGECOINㅇㅅㅇ.xlsx") as string
set destinationPath to (path to desktop as text) & workbookName
save active workbook in destinationPath
end tell
end idle
Sorry in advance if my formatting isn't up to snuff. I'm still a newbie.
Here is a different AppleScript approach which allows you to retrieve your Bitcoin Price values without the need for opening Safari, using JavaScript, Automator, or using text item delimiters. This may not be exactly what you’re looking for but at least it offers a different approach using much less code. Hopefully you can adapt some of it to your needs.
The first 3 properties in the code define the regular expressions which will be used in the do shell script commands, which will extract the dollar values from the HTML source code.
For example, to quickly explain what property eGrepBitcoinPrice : "priceValue___11gHJ\”>\\$\\d{2},\\d{3}.\\d{2}” means… we will be searching for text inside the HTML which contains “priceValue___11gHJ” followed by a “>” followed by “$” followed by any 2 digits followed by a “,” followed by any 3 digits followed by a “.” and followed by any 2 digits
Because I do not have Microsoft Excel, I could not include those commands in the code. However, I did create a quick logging function which writes the prices to a plain text file on your Desktop “Price Log.txt”. This functionality can easily be disabled or removed. The log commands are all wrapped up within a script object called script logCommands which can be removed or commented out along with any other lines in the code which contain my logCommands's.
Here is a snapshot of the log file
Save this following AppleScript code in Script Editor.app as a “stay open” application. Being that it is a “stay open” application, when the applet is launched outside of Script Editor.app, only what is within the explicit on run handler will run only one time. The rest of the magic happens within the on idle handler… and everything within this handler will run every 300 seconds. If you want the commands to repeat every 30 minutes, just set the return value to 1800.
property eGrepBitcoinPrice : "priceValue___11gHJ\">\\$\\d{2},\\d{3}.\\d{2}"
property eGrepLitecoinPrice : "priceValue___11gHJ\">\\$\\d{3}.\\d{2}"
property eGrepDogecoinPrice : "priceValue___11gHJ\">\\$\\d{1}.\\d{5}"
property currentBitcoinPrice : missing value
property currentLitecoinPrice : missing value
property currentDogecoinPrice : missing value
property logToTextFile : missing value
on run -- Executed Only Once.. When This Script Applet Is Launched
activate
set logToTextFile to (display dialog ¬
"Enable Quick Log Mode?" buttons {"No", "Yes"} ¬
default button 2 with title "Log Mode")
if button returned of logToTextFile = "Yes" then
my logCommands's beginLog()
getPrices()
else
getPrices()
return {currentBitcoinPrice, currentDogecoinPrice, currentLitecoinPrice}
end if
end run
on idle
getPrices()
if button returned of logToTextFile = "Yes" then my logCommands's writeToLog()
(* within this idle handler is where you will place
The bulk of your additional code. All of your Excel
Code Goes Here*)
return 300 -- In Seconds, How Often To Run Code In This Idle Handler
end idle
---------- PLACE ALL ADDITIONAL HANDLERS BENEATH THIS LINE ----------
on getPrices()
set currentBitcoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/bitcoin/markets/' " & ¬
"| grep -Eo " & quoted form of eGrepBitcoinPrice & " | cut -c 21-"
set currentLitecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/litecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepLitecoinPrice & " | cut -c 21-"
set currentDogecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/dogecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepDogecoinPrice & " | cut -c 21-"
end getPrices
on quit -- Executed Only When The Script Quits
if button returned of logToTextFile = "Yes" then my logCommands's endLog()
continue quit -- Allows The Script To Quit
end quit
script logCommands
property pathToPriceLog : POSIX path of (path to desktop as text) & "Price Log.txt"
on beginLog()
set startTime to ("Start Time... " & (current date) as text) & ¬
" Price Scanning At 5 Minute Intervals"
do shell script "echo " & startTime & " >> " & ¬
quoted form of pathToPriceLog
end beginLog
on writeToLog()
do shell script "echo " & "Bitcoin:" & quoted form of currentBitcoinPrice & ¬
" Dogecoin:" & quoted form of currentDogecoinPrice & ¬
" Litecoin:" & quoted form of currentLitecoinPrice & ¬
" " & quoted form of (time string of (current date)) & ¬
" >> " & quoted form of pathToPriceLog
end writeToLog
on endLog()
set endTime to quoted form of "End Time... " & (current date) as text
do shell script "echo " & endTime & " >> " & ¬
quoted form of pathToPriceLog
do shell script "echo " & " " & " >> " & ¬
quoted form of pathToPriceLog
end endLog
end script
Unfortunately “stay open” applications and scripts when launched from within Script Editor.app, will not execute what is within the idle handler. So the “stay open” application needs to be launched from within Finder, like any other applications, to observe the results of the idle commands as they are happening. This was the main reason I included a logging to file function… so I could observe the results of the idle commands in real time.
Contrary to what a lot of people think, most “stay open” applications use very little system resources.
UPDATED APPLESCRIPT CODE DUE TO CHANGED URL SOURCE CODE
property eGrepBitcoinPrice : "priceValue\\ \">\\$\\d{2},\\d{3}.\\d{2}"
property eGrepLitecoinPrice : "priceValue\\ \">\\$\\d{3}.\\d{2}"
property eGrepDogecoinPrice : "priceValue\\ \">\\$\\d{1}.\\d{4}"
property currentBitcoinPrice : missing value
property currentLitecoinPrice : missing value
property currentDogecoinPrice : missing value
property logToTextFile : missing value
on run -- Executed Only Once.. When This Script Applet Is Launched
activate
set logToTextFile to (display dialog ¬
"Enable Quick Log Mode?" buttons {"No", "Yes"} ¬
default button 2 with title "Log Mode")
if button returned of logToTextFile = "Yes" then
my logCommands's beginLog()
getPrices()
else
getPrices()
return {currentBitcoinPrice, currentDogecoinPrice, currentLitecoinPrice}
end if
end run
on idle
getPrices()
try
if button returned of logToTextFile = "Yes" then my logCommands's writeToLog()
on error errMsg number errNum
my logCommands's writeToLog()
end try
(* within this idle handler is where you will place
The bulk of your additional code. All of your Excel
Code Goes Here*)
return 300 -- In Seconds, How Often To Run Code In This Idle Handler
end idle
---------- PLACE ALL ADDITIONAL HANDLERS BENEATH THIS LINE ----------
on getPrices()
set currentBitcoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/bitcoin/markets/' " & ¬
"| grep -Eo " & quoted form of eGrepBitcoinPrice & " | cut -c 14-"
set currentLitecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/litecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepLitecoinPrice & " | cut -c 14-"
set currentDogecoinPrice to do shell script ¬
"curl --no-keepalive 'https://coinmarketcap.com/currencies/dogecoin/' " & ¬
"| grep -Eo " & quoted form of eGrepDogecoinPrice & " | cut -c 14-"
end getPrices
on quit -- Executed Only When The Script Quits
if button returned of logToTextFile = "Yes" then my logCommands's endLog()
continue quit -- Allows The Script To Quit
end quit
script logCommands
property pathToPriceLog : POSIX path of (path to desktop as text) & "Price Log.txt"
on beginLog()
set startTime to ("Start Time... " & (current date) as text) & ¬
" Price Scanning At 5 Minute Intervals"
do shell script "echo " & startTime & " >> " & ¬
quoted form of pathToPriceLog
end beginLog
on writeToLog()
do shell script "echo " & "Bitcoin:" & quoted form of currentBitcoinPrice & ¬
" Dogecoin:" & quoted form of currentDogecoinPrice & ¬
" Litecoin:" & quoted form of currentLitecoinPrice & ¬
" " & quoted form of (time string of (current date)) & ¬
" >> " & quoted form of pathToPriceLog
end writeToLog
on endLog()
set endTime to quoted form of "End Time... " & (current date) as text
do shell script "echo " & endTime & " >> " & ¬
quoted form of pathToPriceLog
do shell script "echo " & " " & " >> " & ¬
quoted form of pathToPriceLog
end endLog
end script
I'm working on an AppleScript that is calling a Python script with the name of a file as an argument, something like :
set descriptionFiles to (every file of current_folder whose name extension is "txt")
repeat with textFile in descriptionFiles
-- run a Python script that clears the xml tags and reformat the text of the file
do shell script "python3 '/Users/MBP/Documents/Python/cleanDescription.py' '" & textFile & "'"
end repeat
Now the AppleScript does fine as long as I'm not encountering a file with a single quote in it's name at which point it stops and throws an error.
To correct that, I've been trying to escape the single quote in the files name before passing it to the Python script but that's where I'm stuck. I'm using this routine :
on searchReplace(thisText, searchTerm, replacement)
set AppleScript's text item delimiters to searchTerm
set thisText to thisText's text items
set AppleScript's text item delimiters to replacement
set thisText to "" & thisText
set AppleScript's text item delimiters to ""
return thisText
end searchReplace
with a call like this :
tell application "Finder"
set search_T to "'"
set rep to "\\'"
set selected to selection as alias
set textName to selected as text
set res to searchReplace(textName, search_T, rep)
end tell
Using the code above on a single file throws an error on the searchReplace(textName, search_T, rep) part, with a number of -1708
Any ideas ?
The most reliable way to escape special characters in AppleScript is quoted form of. It handles all forms of quotation smoothly. Never do it yourself. It's also a good practice to quote paths always in do shell script lines even if they don't contain spaces.
Another issue is that textFile is supposed to be a POSIX path rather than a Finder specifier. And get the path to the python script once
set pythonScriptPath to POSIX path of (path to documents folder) & "Python/cleanDescription.py"
set descriptionFiles to (every file of current_folder whose name extension is "txt")
repeat with textFile in descriptionFiles
-- run a Python script that clears the xml tags and reformat the text of the file
do shell script "python3" & space & quoted form of pythonScriptPath & space & quoted form of POSIX path of (textFile as text)
end repeat
I have a text file that is automatically generated from a machine. The machine writes the txt file in "chunks" (sorry I don't know the exact terminology). I need to pull data from this txt file, but I need the txt file to be finished before pulling data from it. I found a solution to verify that the machine has finished writing to the file... It is not as elegant as i had hoped, but seems to do the trick. Excel VBA opens a command prompt, the command prompt uses a Find command to find the string "End of Report"... This is basically one of the last lines of the txt file and pretty safe to assume the txt file is finished after this is found. This code runs in a loop 1000 times, every 10 seconds, until it finds this string or reaches 1000 tries...
The issue is that "result" returns some other characters besides just "End of Report" this is further complicated by the fact that I am attempting to run this on some csv files too... and "result" returns some additional characters also, but different from the ones returned from the txt files. For example, if I check the length of "result"... The length comes back as 43 on one file and 48 on another file... I think it is counting the file path + "End of Report" + a few more characters?
Anyways, I don't really need the "result"... I really only need a "true" / "false" if "Find" found "End of Report" or not... How can I accomplish this? Is there a different better way to do this? I am not familiar with command prompt programming.
Note: It is important that I search these files without opening them.
Sub test()
Dim SearchStr As String
Dim cmdLine As Object
Dim result As String
Dim FilePath As String
FilePath = "D:\test2.txt"
SearchStr = """End of Report"""
Set cmdLine = CreateObject("WScript.Shell")
result = cmdLine.Exec("%comspec% /C Find " & SearchStr & " " & Chr(34) & FilePath & Chr(34)).STDOut.ReadAll
Debug.Print (result)
End Sub
I am not really an expert in command line, but what I would do is export the result of the FIND command to a file, like here
Then I would check in your VBA code how many rows are in the file (either clean the file before, or check the number of rows before the export is done).
If the number of rows meets the criteria (probably 2 or more rows instead of 1), then you can set the flag to True.
I am trying to build an AppleScript that reads each line of a “.txt” file (with a linefeed) and stores the contents of each line into AppleScript variables.
Here is what I mean:
Let’s say there was a “Test.txt” file with the contents:
Apples
Oranges
Pears
As you can see, the “Test.txt” file’s contents have a String on each line, a linefeed introducing the new String, and so on.
I would really like to know how an AppleScript could be made so that each line’s Strings are copied into individual AppleScript variables.
(This way, “Apples” in the first line, would be stored in variableA, “Oranges” in the next would be stored in variableB, “Pears” … variableC, etc.)
Please let me know, from your experience, how best to accomplish this. I know it’s slightly more involved, here is where I am:
(*
This portion of the AppleScript accesses the contents of the ".txt" file named "Test," though takes all of the content and places it into a single variable.
*)
set newFile to ("Macintosh HD:Users:Username:Desktop:Test.txt")
set theFileContents to (read file newFile)
{ AppleScript code to read each line to individual variables }
I know there must be others trying to accomplish this.
This example is for a situation where you know the anticipated paragraphs you'll be looking for to assign to each of a known set of variables.
set newFile to ("Macintosh HD:Users:Username:Desktop:Test.txt")
set theFileContents to paragraphs of (read file newFile)
set recipientEmail to paragraph 1 of theFileContents as text
set senderEmail to paragraph 2 of theFileContents as text
set theSubject to paragraph 3 of theFileContents as text
set theBody to (paragraphs 4 thru -1 of theFileContents) as text
Another option would be to dynamically search for a string in the paragraph, and if it matches, then assign it to that variable. Something like:
set newFile to ("Macintosh HD:Users:jweaks:Desktop:horses.txt")
set theFileContents to paragraphs of (read file newFile)
set recipientEmail to ""
set senderEmail to ""
set theSubject to ""
set theBody to ""
repeat with p in theFileContents
if p contains "To:" then
set recipientEmail to p
else if p contains "From:" then
set senderEmail to p
else if p contains "Subject:" then
set theSubject to p
else
set theBody to theBody & p & return
end if
end repeat
Thank you so much for all of your effort to answer this question, jweaks. As I am still catching on to AppleScript best practices, I was thinking more about your recommendation of bringing the contents of the “.txt” file into a list, assigning the items to AppleScript variables (if needed), and began brainstorming how to accomplish it. I agree that it seems like the simplest and most efficient approach:
Reads the “.txt” file’s into a list of items: Apples, Oranges, and Pears
set paragraph_list to read file "Macintosh HD:Users:tombettinger:Desktop:Test.txt" using delimiter linefeed
Apples
set variableA to item 1 of paragraph_list
Oranges
set variableB to item 2 of paragraph_list
Pears
set variableC to item 3 of paragraph_list
Displays the contents of each variable (optional comment)
display dialog variableA & " " & variableB & " " & variableC
End of AppleScript
As long as the contents of the ".txt" file are stacked in a table, this approach will support the accessibility of information I was searching for. Thanks again!
I have about 400 excel files. I want to insert a column just before the first column in the existing file and then insert the name of the file into each row of that column.
I know a little bit of Applescript and based on that I wrote this script so that I can drop some files onto the script and it will execute the script on each one of those files.
I was wondering if someone could help me in completing the "TO DO" lines. Upon execution this script gives me dialogue boxes with the path of files that I drop on top. But the excel application throws an error dialogue box which says" Not enough memory". I tried this with only 2 excel files so it wasn't the number of files that caused the error.
Can someone please give me a hand with completing the TODO lines and give me an ide as to why Im getting the error. Thanks
property numFiles : 0
on open excelFiles
set fileNames to ""
tell application "Finder"
repeat with eachFile in excelFiles
--open document file eachFile
--tell application "Microsoft Excel"
--increment count
--save name of each file
set fileNames to fileNames & return & (POSIX path of eachFile)
--TO DO insert a column
--TO DO insert text in each column to the name of eachFile
--end tell
end repeat
display dialog fileNames
--display dialog "Ouch that hurt " & return & "You dropped " & (count excelFiles) & "files on me"
end tell
end open
on addFilePath(eachFile)
set fileNames to fileNames & (POSIX path of eachFile)
end addFilePath
Thanks a lot
I don't understand everything --> insert the name of the file into each row of that column | TO DO insert text in each column to the name of eachFile.
Here is the script, Updated :
on open excelFiles
set numFiles to count excelFiles
repeat with eachFile in excelFiles -- open each file in Excel
tell application "Microsoft Excel"
set tBook to open workbook workbook file name (eachFile as string)
set tName to name of tBook
insert into range column 1 of active sheet -- insert column
set lastCell to last cell of used range of active sheet -- get last cell from the used range
set value of range ("A1:A" & first row index of lastCell) of active sheet to tName --set first column's values to the file name
close tBook saving yes
end tell
end repeat
display dialog numFiles
end open
Edit : I forgot the error :
Not enough memory : This weird error seems to be : you call a handler without using my or tell me to) in a tell block application.
Use my like this : set x to my addFilePath(eachFile)
Also, a tell application "Microsoft Excel" block in the application Finder block is not recommended, this can cause unexpected errors.