I need to have an AppleScript that will edit the contents of a given text file (generic structure) and delete the 5th character through 8th character, leave characters 9-20, and delete characters 21-32. For example:
Say this is my text file:
"
Qt&:$yp$shshshahahah$jsjsjajssjh
"
(Single line)
I would need to delete starting from the first $ to the next $, and then delete everything after (including) the last $. In this example, the end result would be this:
Qt&:shshshahahah
Thanks,
Isaac D'Keefe
You could run a command like this in Terminal:
sed -Ei '' 's/(.{4}).{4}(.{12}).*/\1\2/' ~/Documents/file
Or if you need to use AppleScript:
set p to "/Users/username/Documents/file"
set input to read p as «class utf8»
set input to text 1 thru 4 of input & text 9 thru 20 of input
set fd to open for access p with write permission
set eof fd to 0
write input to fd as «class utf8»
close access fd
I would need to delete starting from the first $ to the next $, and
then delete everything after (including) the last $. In this example,
the end result would be this:
Based on these conditions you can split an string up into chunks using a delimiter/separator. Then to my understanding you only want to keep the odd items and remove the even ones (by index). So the following script will work as you described rather than working on the index of the characters.
set theString to " Qt&:$yp$shshshahahah$jsjsjajssjh "
set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "$"}
set textItems to every text item of theString
set AppleScript's text item delimiters to oldTID
set filteredTextItems to {}
repeat with x from 1 to count textItems by 2
set end of filteredTextItems to item x of textItems
end repeat
return filteredTextItems as string
Related
I want to create a Mac app similar to Textexpander or Atext. Both these applications allow the user to define snippets along with their respective trigger words. Typing the trigger words in any app, replaces that trigger word with the actual snippet defined.
I presume that the app listens to all strings being typed in any app and when it detects a string matching one of the trigger words defined, it replaces it with the snippet.
Is that how it actually works, or is there some other way?
Make two fields. In field 2 put something like:
time xyz
come ABC
In the script of field 1:
on textChanged
if the last char of me = space then
put the last word of me into temp
if temp is in fld 2 then
repeat for each word tWord in fld 2
put the last word of line lineOffset(temp,fld 2) of fld 2 into the last word of me
exit repeat
end repeat
end if
select after text of me
end if
end textChanged
Now type into fld 1, you know, "Now is the time for all good men to come to the aid of their country". This can be better done with an array, but the concept may be more accessible here.
This is a better handler, since it will not react to the trigger word:
on textChanged
if the last char of me = space then
put the last word of me into stringOfInterest
put fld 2 into dataToSearch
if stringOfInterest is in dataToSearch then
repeat for each line tLine in dataToSearch
if word 1 of tLine = stringOfInterest then
put word 2 of tLine into the last word of me
exit repeat
end if
end repeat
end if
select after text of me
end if
end textChanged
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 want Applescript to set variables from a txt file, read line by line or character by character. Maybe like the php function: get_file_contents. Is there anything similar or could you please provide me the way?
I know how to set the file path. It's like
set myfile to "/Users/Username/Desktop/test.txt"
set theText to read myfile
In the txt file, it's just one integer in one line, like
1
2
3
4
5
If I use
set theTextList to paragraphs of theText
the result will have quotation marks "".
I just want to set these integer numbers to a variable. So that later I could use, like
set variable to 5 --here I would like to replace the real number 5 to the number I read from the txt file(just one line)
start slideshow
show slide variable
Thanks in advance for your help.
If the lines of the file are delimited by return characters, something like this should work:
set allRecords to read myfile using delimiter return
repeat with aRecord in allRecords
if length of aRecord is greater than 0 then
set variable to aRecord
log "variable: " & variable
end if
end repeat
You can change the delimiting character in the first line of the code if in your file is something different than return.
I would like to read in a CSV file in as a 2D array and then return it back to a CSV file.
Let's say that this is my CSV file. It is an excel file and the | implies the adjacent cell:
family | type
Doctor | Pediatrics
Engineer | Chemical
From what I understand, there are no arrays on applescript, just lists and records. If it would be better to do this with a XLSX file, please let me know.
Nigel's CSV-to-list converter is the best I have seen ...
http://macscripter.net/viewtopic.php?pid=125444#p125444
For your example, use these settings:
set csvText to "family | type
Doctor | Pediatrics
Engineer | Chemical"
csvToList(csvText, {separator:"|"}, {trimming:true})
v2
set csvText to read "/Users/user1385816/Desktop/yourfile.csv"
csvToList(csvText, {}, {trimming:true})
An array is just a list in applescript, so you want a 2d array or a list-of-lists in applescript-speak. If you understand applescript's text item delimiters then your task is just simple manipulation to convert strings into lists and vice versa. So I wrote you a couple handlers to make the task easy for you; textToTwoDArray() and twoDArrayToText(). This first example shows how to convert your string into a list-of-lists using textToTwoDArray().
NOTE: you have to be careful of the line endings in a text file because they can be either a carriage return (character id 13) or a line feed (character id 10). You can see I used character id 10 in my code but if you aren't getting the proper results try "13".
set fileText to "family | type
Doctor | Pediatrics
Engineer | Chemical"
textToTwoDArray(fileText, character id 10, " | ")
on textToTwoDArray(theText, mainDelimiter, secondaryDelimiter)
set {tids, text item delimiters} to {text item delimiters, mainDelimiter}
set firstArray to text items of theText
set text item delimiters to secondaryDelimiter
set twoDArray to {}
repeat with anItem in firstArray
set end of twoDArray to text items of anItem
end repeat
set text item delimiters to tids
return twoDArray
end textToTwoDArray
And here's how to convert a list-of-lists back into your string using twoDArrayToText().
set twoDArray to {{"family", "type"}, {"Doctor", "Pediatrics"}, {"Engineer", "Chemical"}}
twoDArrayToText(twoDArray, character id 10, " | ")
on twoDArrayToText(theArray, mainDelimiter, secondaryDelimiter)
set {tids, text item delimiters} to {text item delimiters, secondaryDelimiter}
set t to ""
repeat with anItem in theArray
set t to t & (anItem as text) & mainDelimiter
end repeat
set text item delimiters to tids
return (text 1 thru -2 of t)
end twoDArrayToText
So now all you have to do is figure out how to read and write to a text file with applescript. Good luck ;)
If your question is just about modeling your CSV data in AppleScript, the solution is to use a list of records like this:
set csvData to {{family:"Doctor", type:"Engineer"}, {family:"Engineer", type:"Chemical"}}
you can then read that out again inside a repeat with aRow in csvData loop.
A technical note: AppleScript lists are implemented as vectors, meaning they are ordered and can be accessed by numerical index (beginning at index 1) – they behave much like an array in most other languages.
In Applescript I have a string of single digit numbers:
0123456789
I want to go through that string and add a comma between each number, so it would show:
0,1,2,3,4,5,6,7,8,9
How can I do this with Applescript?
Notes
I want both the input and output to be of type "string" - not list.
The numbers will always be single digit numbers.
You can use a handy feature called AppleScript's text item delimiters, which allows you to break up (or "parse" in computer jargon) text into segments, and then extract data from those segments. They are the separators of text items in a piece of text. A simple example:
set prevTIDs to AppleScript's text item delimiters
set theString to "Don't-eat-the-yellow-snow"
set AppleScript's text item delimiters to "-" --tell AppleScript to break up strings at each occurrence of a hyphen '-' in a given string
set these_items to every text item of theString
//--> {"Don't", "eat", "the", "yellow", "snow"}
set AppleScript's text item delimiters to prevTIDs
return these_items
It is always considered good practice when working with text item delimiters to restore the original delimiters; once you change the delimiters, they will globally affect the running environment until the process is closed and restarted.
Another use for text item delimiters is replacing words or characters in a given string:
set prevTIDs to AppleScript's text item delimiters
set theString to "Don't eat the yellow snow"
set AppleScript's text item delimiters to "yellow" --the word you want to replace
set temp to every text item of theString
//--> {"Don't eat the", "snow"}
set AppleScript's text item delimiters to "pink" --the replacement word
set theString to temp as string
set AppleScript's text item delimiters to prevTIDs
return theString
//--> "Don't eat the pink snow"
However, note that this replaces every occurrence of the word "yellow". The reason I'm saying this is consider the following string:
If someone added one plus one, what would be the result?
If you wanted to replace the word "one" with the word "two", you would have to be sure to precede "two" with a space when creating the new delimiter, or your resulting string would be the following:
If sometwo added two plus two, what would be the result?
What you're trying to do is basically replacing empty strings with commas. All you need to do is follow these simple steps to do this:
Create a variable to store the current delimiters in
Create a variable to store your string in
Change the delimiter to an empty string ""
Coerce your string into a list (i.e. set the list to every text item of yourString)
Change the delimiter to a comma ,
Coerce your newly created list back into a string (i.e. set yourString to list as string)
Restore the old delimiters
return your string
The resulting code:
set prevTIDs to AppleScript's text item delimtiers
set myString to "0123456789"
set AppleScript's text item delimiters to ""
set the_list to every text item of myString
set AppleScript's text item delimiters to ","
set myString to the_list as string
set AppleScript's text item delimiters to prevTIDs
return myString
Happy coding! :)
Something like this?
set theNumber to "3452678190"
set AppleScript's text item delimiters to ","
set theItems to every character of theNumber as string
set AppleScript's text item delimiters to ""
return theItems