Test for a specific character with a .txt file (Applescript) - macos

Hi Applescript Stackoverflow Community!
I am attempting to write a code in which a different action will occur depending on the 1st character of a .txt file. This is my code so far (I'm fairly new to Applescript so I'm sorry if this is a basic question).
if first character of "/Users/Goombado/Documents/applescript_test.txt" is 1 then
display dialog "Hi"
else
display dialog "Hello"
end tell
end if
Is it possible to do this in Applescript or not?
Thanks in advance :)

You're not so far.
1) instruction "end tell" should always be after a "tell application" instruction. But in this case, there is no need to call any application.
2) you need to tell the script to read the text file, and the file paths in script are using ":". You can use also paths with "/" separator, but then via posix conversion.
set C1 to first character of (read file "Users:Goombado:Documents:applescript_test.txt")
if C1 = "1" then
display dialog "Hi"
else
display dialog "Hello"
end if
Note : You should avoid to hardcode path and file name.

Related

Record the file paths of all open documents in AppleScript

I am a newbie scripter in AppleScript.
I have some applications in which I have many windows or tabs opened. I would like to record their file paths or url in text files, so that I will be able to examine them later.
I could get the path of the front document in Preview:
tell application "Preview"
path of front document
end tell
But when I try:
tell application "Preview"
repeat with i in all documents
path of front document i
end repeat
end tell
this does not compile, with the error message: "Expected end of line but found plural class name."
I would very much appreciate for any insight that would help me.
Thank you very much in advance
ni
You can obtain paths to all open documents at once:
tell application id "com.apple.Preview" to set filepaths to the path of every document
Here's a trick to create a blank file if it doesn't already exist:
set f to "/Users/<you>/PreviewFileList.txt"
close access (open for access f)
# set eof of f to 0 -- This scrubs the file if it does already exist
The variable filepaths will be an AppleScript list, which you want to turn into a single piece of text that, say, itemises each filepath, one-per-line (assuming none of your file paths have newline characters in their names):
set my text item delimiters to linefeed
set filepaths to filepaths as text
This coerces the list to a text class object, thereby concatenating each item in the list with adjoining linefeed (\n) characters. That is to say, this:
{"/path/to/file.one", "/path/to/file.two", ..., "/path/to/file.nth"}
becomes this:
"/path/to/file.one
/path/to/file.two
.
.
.
/path/to/file.nth"
This is now stored in the filepaths variable, overwriting its previous value (we don't need the list object anymore).
Finally, write the text out to file, which will need to be explicitly encoded as UTF-8 in order to preserve Japanese characters when they are decoded as UTF-⒏ So, we do this as follows:
write (the filepaths & linefeed) as "utf8" to f starting at eof
(Adding a linefeed at the end is convention, and helps ensure that the next time you write to the same file, new content is added to the line below rather than the end of the sentence.)
Here's the whole script:
tell application id "com.apple.Preview" to set filepaths to the path of every document
set f to "/Users/<you>/PreviewFileList.txt"
close access (open for access f)
# set eof of f to 0
set my text item delimiters to linefeed
set filepaths to filepaths as text
write (the filepaths & linefeed) as "utf8" to f starting at eof
tell application id "com.apple.Finder" to reveal the POSIX file named f
There is no syntax all documents
It's either
tell application "Preview"
repeat with i in documents
path of i
end repeat
end tell
or
tell application "Preview"
repeat with i in every document
path of i
end repeat
end tell
or if you need the numeric index
tell application "Preview"
repeat with i from 1 to (count documents)
path of document i
end repeat
end tell
And front in a loop makes no sense because there is only one front document or window

Applescripts. How do I add a text_object/code snippet to the end of certain lines in a text document?

I'm using an Applescript to find-and-replace certain characters or strings of characters in BBEdit to speed up the process of ripping content out of a Microsoft Word document and wrapping it in html before it goes into a CMS. Most of this is fine when it's a replace-all type of command. However, I can't figure out how to amend the end of a line with a closing H tag.
For instance, the following line does a great job of wrapping paragraphs in P tags:
replace "\\n\\n" using "</p>\\n<p>" searching in text 1 of text document 1 options {starting at top:true}
And I have a solution for adding h tags to the front of the a line. However, I can't figure out how to amend the end of a line with a closing h tag, and that's what I'm hoping to get some help with.
I'm looking for something that follows this logic: "If a line begins with <h3>, add </h3> to the end of the line." OR "When a line begins with <h3>, replace the next \\n with </h3>\\n."
If there's something that works within the Applescript (rather than a shell), that would be ideal, as I am fairly new to this and haven't taught myself anything about shells just yet.
You can solve this efficiently using BBEdit's built in regular expressions support, like so:
tell application "BBEdit"
tell text window 1
tell contents
replace "^(\\<h3\\>)(.*)$" using "\\1\\2<\\\\h3>" options {search mode:grep, starting at top:true}
end tell
end tell
end tell
This adds closing tags for all h3 elements.
I figured it out after one of the respondents to my original post pointed me in the right direction. (This exchange in a Google Group was also pretty helpful.)
I don't know if this is "correct" but it does what I was hoping it could do: It adds a string to the end every line that begins with something specific.
-- This tell will find h3 tags and add a closing tag to the end of the line. It adds a space before the opening h3 tag so that it won't loop forever, and then the second tell removes that extra space once the loop finishes.
tell application "BBEdit"
tell text window 1
set loop_while_true to true
repeat while true
set find_h3 to find "^<h3>(.*)" options {search mode:grep, starting at top:loop_while_true} with selecting match
set loop_while_true to false
if found of find_h3 then
set my_h3 to found text of find_h3
replace my_h3 using (" " & my_h3 & "</h3>\\n") options {starting at top:true, returning results:true, wrap around:true}
else
exit repeat
end if
end repeat
end tell
end tell
-- this will clean up the extra space introduced during the loop sequence.
tell text 1 of text document 1
replace " <h3>" using "<h3>" options {search mode:grep, starting at top:true, returning results:true, wrap around:true}
end tell

Take X Symbols After a Marker and Save to Variable in AppleScript

I'm looking for a way via AppleScript to take 11 symbols after ?v= part in an URL that's in clipboard and save them into a variable. Here's an example of a link:
https://www.youtube.com/watch?v=PxDK95Q5qN0&ab_channel=TheLateShowwithStephenColbert
So I need a little script that would take a link in clipboard, identify 11 symbols after ?v=, take those 11 symbols (PxDK95Q5qN0) from that link and save it into a variable (e.g. extract).
I did find a partial solution here — but that one only works when it's BETWEEN two parts e.g. ?v= and &. The problem with that solution is that many links are short and do not have the last & symbol (e.g. https://www.youtube.com/watch?v=PxDK95Q5qN0)
I'd appreciate any help or pointers here! :]
Whether you set the clipboard to, e.g.,:
set the clipboard to "https://www.youtube.com/watch?v=PxDK95Q5qN0&ab_channel=TheLateShowwithStephenColbert"
Or, e.g.,:
set the clipboard to "https://www.youtube.com/watch?v=PxDK95Q5qNO"
The following example AppleScript code returns the eleven characters after ?v=:
set extract to do shell script ¬
"sed -Ee 's/.*[?]v[=]([a-zA-Z0-9_-]{11}).*/\\1/'<<<" & ¬
(the clipboard as text)'s quoted form
Note that \\?v\\= can be used instead of the [?]v[=] portion of the sed command as in either case the ? and = are treated as regular characters instead of shell special characters.
Additionally, if the number of target characters changes from 11 yet ?v= and & are still in play, as in your examples, then this regex, with explanation shown further below, handles it:
.*[?]v[=]([a-zA-Z0-9_-]+[^&]).*
Notes:
If the 11 target characters contain other than what is shown in the capturing group:
([a-zA-Z0-9_-]{11})
Then modify it as needed.
Using info from https://regex101.com to explain the regex used in the sed command:
The main part of interest is the Capturing Group ([a-zA-Z0-9_-]{11}), as this is what's returned, if it exists directly after ?v= in the URL.
When Capturing Group is: ([a-zA-Z0-9_-]+)
That macsripter link points you in the right direction (though it's a lot of information to digest). As long as you're running 10.6 or later, you can use this routine:
on getTheV(link_text)
set {tid, my text item delimiters} to {my text item delimiters, {"=", "&"}}
set theV to second text item of link_text
set my text item delimiters to tid
return theV
end getTheV
which breaks the link up into text items — split on '=' and '&' — and returns the second item.
Use it like so:
set theV to getTheV("http://...")
Both the links you provided return the correct value.

Adding if-else Logic to My Applescript (depending on whether a FIND gets a match)

I've got an applescript that does lots of text manipulation, then searches for a text string, selects that text string, runs a python script on the selection, inserts the output, and selects and copies that output. Then the applescript procedes with more actions.
Problem: the text string searched for and operated on by that Python script isn't always present. If not, I'd want it to jump past the python part and resume the rest of my applescript.
Here's the salient part of the script, below. I'll start out with the final action of my AppleScript before the Python script cuts in:
replace "Claimed" using "" searching in text 1 of text document 1 options {starting at top:true, case sensitive:true}
#here is where my script searches for the text string the Python script will operate on (and which may NOT be present):
find "^Mon .+" searching in text 1 of text document 1 options {search mode:grep, wrap around:true, case sensitive:true} with selecting match
#here's the python part (which shouldn't be triggered if the string, above, isn't found):
set unprocessed to contents of selection
set processed to (do shell script ("python ~/Library/Scripts/yelpmanip.py '" & unprocessed & "'"))
set contents of selection to processed
copy selection
#If python script didn't run, I'd want to resume below:
find "events" searching in text 1 of text document 1 options {search mode:grep, wrap around:true} with selecting match
tell application "System Events" to key code 126 using {shift down, command down}
#etc etc
end tell
You just use set match to find ... to grab the result, and check using the syntax if found of match.
Source: https://nathangrigg.com/2012/06/bbedit-search-with-applescript.
Code (not tested):
replace "Claimed" using "" searching in text 1 of text document 1 options {starting at top:true, case sensitive:true}
#here is where my script searches for the text string the Python script will operate on (and which may NOT be present):
set match to find "^Mon .+" searching in text 1 of text document 1 options {search mode:grep, wrap around:true, case sensitive:true} with selecting match
#here's the python part (which shouldn't be triggered if the string, above, isn't found):
if found of match then
set unprocessed to contents of selection
set processed to (do shell script ("python ~/Library/Scripts/yelpmanip.py '" & unprocessed & "'"))
set contents of selection to processed
copy selection
end if
#If python script didn't run, I'd want to resume below:
find "events" searching in text 1 of text document 1 options {search mode:grep, wrap around:true} with selecting match
tell application "System Events" to key code 126 using {shift down, command down}
#etc etc
end tell

Cucumber Ruby read Word Doc or Text

I'm writing tests that will be confirming a lot of text on page. It's for Terms and Conditions pages, Cookies, Privacy Policy etc. Not what I'd like to do but it's a requirement I can't avoid. I've heard that Cucumber can open a text file like. txt or .doc and compare the text on screen.
I've tried to find any reference to this but have come up short. Is anyone able to point me in the right direction please?
Thanks
Cucumber/aruba has a Given step that goes like this :
Given a file named "foo" with:
"""
hello world
"""
You would then be able to check that you webpage has content with :
Then I should see "hello world"
And your step :
Then /^I should see "([^"]*)" do |text
(page.should have_content(text))
I continued to play and found this works for a .txt file:
File.foreach(doc) do |line|
line = line.strip
within_window(->{ page.title == 'Cookies' }) do
page_content = find('#main').text
page_content.gsub!('‘',"'")
page_content.gsub!('’',"'")
expect(page_content).to have_text line
end
end
end
doc is my filename variable. I used strip to remove the newline characters created when pasting into the txt file. The cookies open up in a new tab so I navigated to that. I had invalid UTF-8 characters so just used gsub on those.
I'm sure there's a much better way to do this but this works for now
I'd recommend using approval tests. A person approves the original, then the automated test verifies no change. If the license text changes, the test fails. If the text is supposed to pass, then the tester approves the new text, then it's automated thereafter.

Resources