Applescript, read lines as variables - text

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.

Related

AppleScript, can't replace character in a text

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

read first 1000 characters of text file in VBA

Am using the following command to read the first 1000 characters of a huge txt file.
text = Input$(1000, 1)
problem is when I want to display a character in a textbox, it displays a newline character at the end (a reverseP) which I dont want.
The other option i have is to read the first 1000 characters using a Do-Until loop like the following. However, could not find a command to replace EOF(1).
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
can somebody provide any help with this ?

AppleScript to read strings from ".txt" files to variables

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!

AppleScript and .txt file

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

Retrieving last line of a txt file with a VBscript

Before all, I want to say that I am not a programmer, so this may be basic for some people but surely not for me!!
The task that I want to accomplish is to retrieve some characters of a data file that is imported automatically from a server.
Data is stored in lines in a CSV or tabbed .txt file, each line consists of date and some numeric values. The format is always the same, only the file grows in one line each time a new value is entered.
What I need the script to do, is open that file (wich adress is known and constant) search for the last line, and then extract a string from that line and write it on a different .TXT file, from where I can import it to another specific software as a raw value.
The part in the middle (extracting string) is fairly simple, but opening and isolating the last line is far too much for me.
Thanks everybody for helping!
dim path
path = "fileName.txt"
otherOption(path)
function otherOption(fileName)
const read = 1
dim arrFileLines()
set objArgs = CreateObject("scripting.FileSystemObject")
if objArgs.FileExists(fileName) then
set objFile = objArgs.OpenTextFile(fileName,read)
i=0
do until objFile.AtEndOfStream
redim preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
loop
objFile.Close
end if
wscript.Echo arrFileLines(i-1)
end function

Resources