Add character at beginning and end of each line - applescript

I want to cook up an Applescript that adds some characters to the beginning and end of each line of text, like this:
Before script execution:
<div>Something</div>
<div>Something</div>
<div>Something</div>
After script execution:
'<div>Something</div>' +
'<div>Something</div>' +
'<div>Something</div>'
How would you go about scripting something like this? Any hints or ideas is highly appreciated :)

Something like this?
set theFile to (choose file) as string
try
set fd to open for access file theFile
set fileContents to read fd as string
close access fd
on error
close access file theFile
return false
end try
set AppleScript's text item delimiters to "' +" & linefeed & "'"
set newFileContents to "'" & (every paragraph of fileContents) & "'" as string
set AppleScript's text item delimiters to ""
try
set fd to open for access file theFile with write permission
set eof of fd to 0
write newFileContents to fd as string
close access fd
on error
close access file theFile
return false
end try
return true

Related

How to automate the creation of a folder, and a text file within it from CSV data

For each line of a delimited text file, I want to have Automator create a folder named from a field of the source file.
Then in that folder, create a text file named "file.json" with the contents being a string of data from another field of the source file.
The CSV file would have about 100 entries, and probably just two fields like
folderName | { JSON was here }
How would I go about doing that?
I don't know automator so well, but the following AppleScript should do what you want. Does not have much in the way of error checking.
try
set src to (choose file with prompt "choose your input")
set o to (open for access src)
set inputStr to (read o)
close access o
end try
set fldrOut to (choose folder with prompt "choose your output folder")
set atids to AppleScript's text item delimiters
set AppleScript's text item delimiters to "|"
repeat with p in (paragraphs of inputStr)
set folderName to text item 1 of (p as string)
set jsonString to text item 2 of (p as string)
tell application "Finder"
set fldr to (make new folder at fldrOut with properties {name:folderName})
end tell
set pth to (fldrOut as string) & folderName & ":file.json"
set outFile to (open for access pth with write permission)
write jsonString to outFile starting at 0
close access outFile
end repeat
set AppleScript's text item delimiters to atids

Cannot open text file to write to with Apple script

I am trying to create a log of when my computer turns off and on. To do this I am writing a script to run at start up that will write to a text file however it is telling me that I don't have permission to write to the file.
Using print statements I have determined that the try block terminates after the first line.
writeTextToFile(getTimeInHoursAndMinutes(), "Users/labspecialist/Desktop/system_log")
on writeTextToFile(theText, theFile)
try
-- Convert the file to a string
set theFile to theFile as string
-- Open the file for writing
set theOpenedFile to (open for access file theFile with write permission)
-- Write the new content to the file
write theText to theOpenedFile starting at eof
-- Close the file
close access theOpenedFile
-- Return a boolean indicating that writing was successful
return true
-- Handle a write error
on error
-- Close the file
try
close access file theFile
end try
-- Return a boolean indicating that writing failed
return false
end try
end writeTextToFile
on getTimeInHoursAndMinutes()
-- Get the "hour"
set timeStr to time string of (current date)
set Pos to offset of ":" in timeStr
set theHour to characters 1 thru (Pos - 1) of timeStr as string
set timeStr to characters (Pos + 1) through end of timeStr as string
-- Get the "minute"
set Pos to offset of ":" in timeStr
set theMin to characters 1 thru (Pos - 1) of timeStr as string
set timeStr to characters (Pos + 1) through end of timeStr as string
--Get "AM or PM"
set Pos to offset of " " in timeStr
set theSfx to characters (Pos + 1) through end of timeStr as string
return (theHour & ":" & theMin & " " & theSfx) as string
end getTimeInHoursAndMinutes
I expect when I run this to get an output of true and for my file to contain a new line of the current time. However it currently returns false with nothing written to the file.
The problem is that your script is using a file specifier in the open for access line, where it should use a POSIX file specifier (because you're feeding the command a POSIX path). It should look like this:
writeTextToFile(getTimeInHoursAndMinutes(), "/Users/labspecialist/Desktop/system_log")
on writeTextToFile(theText, theFile)
try
-- Convert the file to a string
set theFile to theFile as string
-- Open the file for writing
set theOpenedFile to (open for access POSIX file theFile with write permission)
-- Write the new content to the file
write theText to theOpenedFile starting at eof
-- Close the file
close access theOpenedFile
-- Return a boolean indicating that writing was successful
return true
-- Handle a write error
on error errstr
display dialog errstr
-- Close the file
try
close access file theFile
end try
-- Return a boolean indicating that writing failed
return false
end try
end writeTextToFile
P.s. And yes, you really should use that opening slash in the file path, though it seems to work regardless...

Applescript convert variable into a string with commas for CSV

I have a variable that contains {"THIS", "THAT"} that I am trying to write to a csv so that the csv formats as THIS,THAT. Current it just spits out as THISTHAT.
I think I need to repeat though the variable but I am not sure...
the code is as follows (check the ---> for the important bits):
tell application "Adobe InDesign CC 2014"
delete unused swatches of document 1
set _NotUSED to {"None", "Paper", "Black", "Registration", "Keyline", "ImageLabel", "C=0 M=0 Y=0 K=37", "C=0 M=100 Y=100 K=0", "Map this to white ->", "Dieline", "C=0 M=100 Y=0 K=0"} as string
try
---> Get the variables
set _UpDatedList to get (name of swatches of document 1 whose name is not in _NotUSED)
on error
display alert {"Your document has no spot colours"}
end try
end tell
set filePath to (path to desktop as text) & "Pantones.csv"
---> Set the theString to the variables
set theString to _UpDatedList as string
set theResult to writeTo(filePath, theString, text, false)
if not theResult then display dialog "There was an error writing the data!"
on writeTo(targetFile, theData)
try
set openFile to open for access file targetFile with write permission
---> write the variables to csv
write theData to openFile
close access openFile
return true
on error
try
close access file targetFile
end try
return false
end try
end writeTo
Try this, the easiest way to convert a list to CSV is to use text item delimiters.
The main problem is the coercion to string in the 3rd line. Delete as string.
tell application "Adobe InDesign CC 2014"
delete unused swatches of document 1
set _NotUSED to {"None", "Paper", "Black", "Registration", "Keyline", "ImageLabel", "C=0 M=0 Y=0 K=37", "C=0 M=100 Y=100 K=0", "Map this to white ->", "Dieline", "C=0 M=100 Y=0 K=0"}
try
set _UpDatedList to (get name of swatches of document 1 whose name is not in _NotUSED)
on error
display alert "Your document has no spot colours" buttons {"Cancel"}
return -- abort the script
end try
end tell
set filePath to (path to desktop as text) & "Pantones.csv"
set {TID, text item delimiters} to {text item delimiters, ","}
set csvString to _UpDatedList as text
set text item delimiters to TID
set theResult to writeTo(filePath, csvString)
if not theResult then display dialog "There was an error writing the data!"
on writeTo(targetFile, theData)
try
set openFile to open for access file targetFile with write permission
write theData to openFile
close access openFile
return true
on error
try
close access file targetFile
end try
return false
end try
end writeTo
Here is another option. Just modify your WriteTo handler as shown below to tell it to add a comma after every item in the list, except the last item.
-- Define theString and the target file
set theString to {"This", "That"}
set theFile to (path to desktop as text) & "Pantones.csv"
-- Execute the write handler
set theResult to writeTo (theFile, theString)
on writeTo(targetFile, theData)
set openFile to open for access file targetFile with write permission
set theCount to the count of items in theData
set n to 0
--write to the target file & add a comma after every item except the last
repeat theCount times
set n to n + 1
if n is not theCount then write item n of theData & "," to openFile as string
if n is theCount then write item n of theData to openFile as string
end repeat
close access openFile
end writeTo
In this example, the end result will be your file "Pantones.csv" with the following text:
This,That

Applescript file not found

I am using this syntax in my Applescript but I am getting an error file not found. I am sure the file is there. Is there anything wrong with this?
set rtfFile to "Macintosh HD:Users:ash:Documents:Core:_Marketing:xlsafe_p.rtf" as alias
Here is a little handler to check at which point of your path the error occurs:
set rtfFile to "Macintosh HD:Users:ash:Documents:Core:_Marketing:xlsafe_p.rtf"
checkPath(rtfFile)
on checkPath(aPathToCheck)
set oldATID to AppleScript's text item delimiters
set AppleScript's text item delimiters to {":"}
set pathElements to text items of aPathToCheck
set AppleScript's text item delimiters to oldATID
set d to ""
set tempPath to ""
repeat with i from 1 to (count pathElements)
set tempPath to tempPath & d & item i of pathElements
try
set foo to tempPath as alias
on error
display alert "The path " & return & tempPath & return & "is not valid!" buttons {"OK"}
return false
end try
set d to ":"
end repeat
display alert "The path " & return & tempPath & return & "is valid!" buttons {"Yeah!"}
return true
end checkPath
Here it says The path Macintosh HD:Users:ash is not valid! because I'm logged in with other credentials than you ;-) Please try this handler and tell us the result!
Enjoy, Michael / Hamburg
Try to choose the file with this, copy the text from the alert, and compare the result.
display alert ((choose file) as text)

Use applescript to write iCal data to file

I am trying to get applescript to read todays ical events and write them to a file. The code is as follows:
set out to ""
tell application "iCal"
set todaysDate to current date
set time of todaysDate to 0
set tomorrowsDate to todaysDate + (1 * days)
repeat with c in (every calendar)
set theEvents to (every event of c whose start date ≥ todaysDate and start date < tomorrowsDate)
repeat with current_event in theEvents
set out to out & summary of current_event & "
"
end repeat
end repeat
end tell
set the_file to (((path to documents folder) as string) & "DesktopImage:ical.txt")
try
open for access the_file with write permission
set eof of the_file to 0
write out to the_file
close access the_file
on error
try
close access the_file
end try
end try
return out
The ical items are getting returned correctly and the file ical.txt is created correctly in the folder Documents/DesktopImage, but the file is blank.
Even if I substitute
write out to the_file
with
write "Test string" to the_file
it still comes up blank
any ideas?
Ty
To fix something, you first need to find out what's wrong. You can get the error message when your error handler is invoked, then display it:
on error msg
display dialog "Error accessing " & (the_file as string) & ": " & msg
Once you do this, you quickly see the problem: the_file is a string, not a file, so all the file operations will fail. Define the_file as:
set the_file to alias (((path to documents folder) as string) & "DesktopImage:ical.txt")

Resources