I have a small actionscript.
set lf to ASCII character 10
set csvFile to (choose file with prompt "Select a file to read:")
open for access csvFile
set contentOfCsv to (read csvFile using delimiter {",", lf})
close access csvFile
I want to run a loop to make stuff for each of the parts of "contentOfCsv".
How do I do that?
Thanks
/Erik
Try:
repeat with aPiece in contentOfCsv
display dialog aPiece
-- replace display dialog with code for aPiece
end repeat
I did it like this
set lf to ASCII character 10
set csvFile to (choose file with prompt "Select a file to read:")
open for access csvFile
set contentOfCsv to (read csvFile using delimiter {",", lf})
close access csvFile
repeat with theItem in contentOfCsv
-- Do stuff
end repeat
Related
I have a file (list.txt) with a list that contains thousands of lines that look like this:
carpet-redandblue
shelf-brown
metaldesk-none
Is there a script I can use to remove everything after the "-", including the "-" as well?
This is what I have so far:
set theFile to "/Users/home/Desktop/list.txt"
if theFile contains "-" then
set eol to "-"
else
set eol to "-"
end if
But doesn't seem to be working.
Do I have to define an output file with a filename and path?
This should do what you need, at least as I understand it. The script reads the text file into a variable. It then breaks the text into paragraphs (or lines) and splits each line at the first dash. It then converts each line back into paragraphs of a text. Finally, it writes the resulting text to a text file. If you prefer to use the resulting text in some other way, it is stored in the prunedText variable.
use scripting additions
(*
set rawText to "carpet-redandblue
shelf-brown
metaldesk-none"
*)
set rawText to read file ((path to desktop as text) & "list.txt")
set AppleScript's text item delimiters to "-"
set paraText to paragraphs of rawText
--> {"carpet-redandblue", "shelf-brown", "metaldesk-none"}
set wordPara to {}
repeat with eachLine in paraText
set end of wordPara to first text item of eachLine
end repeat
--> {"carpet", "shelf", "metaldesk"}
set AppleScript's text item delimiters to linefeed
set prunedText to wordPara as text
(*
"carpet
shelf
metaldesk"
*)
-- optionally
tell application "Finder"
set nl to ((path to desktop as text) & "newList.txt") as «class furl»
end tell
close access (open for access nl)
write prunedText to nl as text
This in my opinion is the easiest solution.
Open Terminal.app
Go to Finder and while holding the ⌘ key, drag and drop the folder containing your "list.txt" file directly into a Terminal window. This will change your current working directory in Terminal to the folder containing your "list.txt" file.
Then paste this following code into that Terminal window and press the Return key...
grep -E -o "^\w*" list.txt > new_list.txt
This will create a new file called "new_list.txt" with the hyphens and everything after them removed from each line of your original list.txt
I would like to scan thru my Photo library (macOS 10.15.6, Photos App 5.0) and export selected photos' original file name to a text file. I have a simple script below as a starting point that doesn't properly convert the filename to readable text. I expect I need to execute some kind of 'convert to string' operation on the filename but I'm coming up empty on answers...
Any suggestions would be appreciated
code I'm currently using:
set myFile to open for access "/Users/ed/Desktop/testFile.txt" with write permission
write "file start\n" to myFile
tell application "Photos"
activate
set imageSel to (get selection)
if imageSel is {} then
error "Please select an image."
else
repeat with im in imageSel
write filename of im to myFile
write "\nnext photo\n" to myFile
end repeat
end if
end tell
write "file end\n" to myFile
close access myFile
My suggestion is to build the list of file names, then convert the list to paragraphs with text item delimiters and write the text to disk.
Further it's highly recommended to add reliable error handling to the write part.
tell application "Photos"
set imageSel to selection
if imageSel is {} then
error "Please select an image."
else
set theNames to {"file start"}
repeat with im in imageSel
set end of theNames to filename of im
end repeat
set end of theNames to "file end"
end if
end tell
set {TID, text item delimiters} to {text item delimiters, linefeed}
set theNames to theNames as text
set text item delimiters to TID
set testFile to POSIX path of (path to desktop) & "testFile.txt"
try
set fileDescriptor to open for access testFile with write permission
write theNames to fileDescriptor
close access fileDescriptor
on error
try
close testFile
end try
end try
I'm trying to get a script working which is able to batch export .mts format video files via quicktime into .mov files in 1080p. The script fails with the following error: "The action “Run AppleScript” encountered an error: “QuickTime Player got an error: Can’t make file (document "00000.MTS") into type «class fsrf».”". I assume this has something to do with using text file paths? Note I'm not experienced with Applescript and would really appreciate any help to get this simple bit of script working. Currently it's in automator as a service:
on run {inputFiles}
if inputFiles is equal to {} then
set inputFiles to (choose file with prompt "Select the file(s) to convert:" with multiple selections allowed without invisibles)
end if
open inputFiles
end run
on open droppedItems
tell application "Finder" to set inputFolder to (container of first item of droppedItems) as Unicode text
set outputFolder to (choose folder with prompt "Select output folder:" default location (inputFolder as alias)) as Unicode text
set exportPreset to (choose from list {"Movie", "iPhone", "iPod", "480p", "720p", "1080p"} with prompt "Choose QuickTime Export Preset:") as Unicode text
if exportPreset is equal to "false" then
return
end if
repeat with currentItem in droppedItems
repeat until getProcessPercentCPU("CoreMediaAuthoringSessionHelper") is equal to ""
end repeat
tell application "Finder" to set fileName to name of currentItem as Unicode text
set fileName to text 1 thru ((fileName's length) - (offset of "." in ¬
(the reverse of every character of fileName) as text)) of fileName
convertFile(currentItem, outputFolder & fileName & ".mov", exportPreset)
end repeat
end open
on convertFile(inputFile, outputFile, exportPreset)
tell application "QuickTime Player"
set thisMovie to open inputFile
open for access file thisMovie
close access file thisMovie
export thisMovie in (outputFile) using settings preset exportPreset
close thisMovie
end tell
end convertFile
on getProcessPercentCPU(processName)
do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processName & "$/ {print $1}'"
end getProcessPercentCPU
Try changing:
set outputFolder to (choose folder with prompt "Select output folder:" default location (inputFolder as alias)) as Unicode text
to:
set outputFolder to POSIX path of (choose folder with prompt "Select output folder:" default location (inputFolder as alias))
and:
convertFile(currentItem, outputFolder & fileName & ".mov", exportPreset)
to:
set outputFile to POSIX file (outputFolder & fileName & ".mov")
convertFile(currentItem, outputFile, exportPreset)
and remove the open for access/close access commands.
Sandboxed apps don't like receiving path strings to open/save commands, but accept alias/POSIX file values okay. (If it still doesn't work then it's some other issue at play, but that's always the first thing to check when you get a filesystem permissions error as you describe.)
The error occurs because thisMovie is a document reference of QuickTime Player and this class cannot be converted / coerced to a file system reference («class fsrf»).
That's what the error message says
Can’t make file (document "00000.MTS") into type «class fsrf»
The Standard Additions command open for access does not support QuickTime Player documents anyway. What is the purpose of the open / close lines?
Note:
as Unicode text as coercion to string is outdated since macOS 10.5 Leopard. It's only used with read and write commands to handle UTF16 encoded text. A coercion to standard AppleScript text is simply written as text. In case of name of currentItem it's redundant anyway because the class of name is always text.
I am trying to do below in AppleScript.
Concatenate/Merge all *.xxx files found in a particular folder into one new file
Each file contains a header. Strip header from all but 1st file before merging.
Add a footer text to the merged file.
This sounds relatively simple in other languages but I am a beginner to applescript. Any help to find a direction would be appreciated.
TIA
AnuRV
Try this, you are prompted to choose a base folder and a destination file name.
Important: Use a destination location outside the base folder to avoid the file to be included in the merging process.
I assume that your tsv file type is a typo and you mean csv.
If not, change all occurrences of csv in the script.
The text delimiter is linefeed (0A), if you need return (0D) change the occurrence of linefeed to return.
set baseFolder to choose folder
set destinationFile to choose file name with prompt "Choose destination file name" default name "merged.csv"
tell application "Finder" to set tsvFiles to (files of baseFolder whose name extension is "csv") as alias list
set text item delimiters to linefeed
try
set fileDescriptor to open for access destinationFile with write permission
repeat with i from 1 to (count tsvFiles)
set theFile to item i of tsvFiles
set theText to paragraphs of (read theFile as «class utf8»)
if i = 1 then
write (theText as text) to fileDescriptor as «class utf8»
else
write ((items 2 thru -1 of theText) as text) to fileDescriptor as «class utf8»
end if
end repeat
close access fileDescriptor
on error
try
close destinationFile
end try
end try
set text item delimiters to {""}
I am trying to write a simple logger with Applescript. I have a couple of questions
Firstly I am testing if a file exists, if it does not I want to create a file with that name and set the first line to a string "Counter:0".
So far I have this but my syntax is wrong. Appreciate any help as the info on the web is a bit slender.
tell application "Finder"
set thePath to "/Data/GameLog/"
set theFile to thePath & (do shell script "date '+%Y.%m.%d'" & ".log")
if exists POSIX file thePath then
--display dialog "Found"
else
do shell script "Counter:0" > echo thePath
end if
end tell
secondly I would like to read the first line of the file (ie Counter:0) and increment the integer after the : by 1.
Help v.much appreciated
Based on vadian's answer:
set logFolder to (POSIX path of (path to home folder)) & "Desktop/" -- the trailing slash is crucial
set timeStamp to do shell script "date '+%Y.%m.%d'"
set logFile to logFolder & timeStamp & ".log"
if ((do shell script "test -d " & quoted form of logFolder & "&& echo true||echo false") as boolean) then
try
close access logFile
end try
try
set fileReference to open for access logFile with write permission
on error
display alert "File already open"
return -1
end try
set counter to (get eof of fileReference)
if counter is not 0 then
try
set counter to (read fileReference from 9) as integer
on error
close access logFile
display alert "Read error"
return -1
end try
set counter to counter + 1
set eof of fileReference to 0
end if
write ("Counter:" & counter) to fileReference as «class utf8»
close access logFile
else
display alert "Folder does not exist"
end if
The advantage is that this will not ignore errors. It will also be able to find your home directory without needing you to manually enter it in code. This is safe since we check for the logFolder first. The rest of the code can't fail if that folder exists. I am aware that AppleScript has a method for checking whether or not a file exists, but I have found that functionality to be fairly difficult to use when dealing with POSIX paths, so I'm using a do shell script instead, which naturally deals with POSIX paths.
Please try this, change the file path in the first line (consider the trailing slash)
set logFolder to "/Users/myUser/Desktop/" -- the trailing slash is crucial
set timeStamp to do shell script "date '+%Y.%m.%d'"
set logFile to logFolder & timeStamp & ".log"
try
set fileReference to open for access logFile with write permission
set counter to (get eof of fileReference)
if counter is not 0 then
set counter to read fileReference from 9
set counter to counter + 1
set eof of fileReference to 0
end if
write ("Counter:" & counter) to fileReference as «class utf8»
close access fileReference
on error
try
close access logFile
end try
end try