set textFile to "/Users/whomever/Desktop/TEXT.txt"
Doesn't create a text file anymore. What do I do to make this function work. There is no error.
This following AppleScript code is a basic template demonstrating how to create a text file then write to it.
property textFile : (path to desktop as text) & "TEXT.txt"
set randomText to "Blah Blah Blah"
writeToSomeFile(textFile, randomText) -- Will Create File "TEXT.txt" If Not Exists
-- Additional Code Here
-- More Code Here
tell application "Finder"
activate
reveal textFile
end tell
----- Place Handler Definitions Beneath This Line At Bottom Of Script -----
on writeToSomeFile(pathToFileToWriteTo, someText)
try
set writeToFile to open for access pathToFileToWriteTo with write permission
write someText & linefeed to writeToFile as text starting at eof
close access writeToFile
on error errMsg number errNum
close access alias pathToFileToWriteTo
end try
end writeToSomeFile
However, if you prefer a different option using much less code, this following AppleScript code will achieve the same results.
property textFile : (path to desktop as text) & "TEXT.txt"
set randomText to "Blah Blah Blah"
(* If textFile Does Not Exist Yet, This Will Create The File And Write
randomText To It. Otherwise it will append randomText to the file *)
do shell script "echo " & quoted form of randomText & " >> " & ¬
quoted form of POSIX path of textFile
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 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
I want to read from a text file paragraph by paragraph and since the content of the file is in German language the file contains special characters and I understood I have to use class utf8 in order to read the character properly into the script.
I face the problem if I use the suggested command
set txt to paragraphs of (read foo for (get eof foo)) as «class utf8»
I get the error
error "Can’t make {\"\tDate:\t10. J√§nner 2006 20:53\", \"\tTags:\tHase, Muffin, Paul\", \"\tLocation:\tM√ºhlgasse, Wiener Neudorf, Lower Austria, Austria\", \"\tWeather:\t-7¬∞ Clear\", \......
If I read the file without the «class utf8» no error occurs.
I use the following code:
set theFile to readFile("/Users/Muffin/Documents/DayOne-Export/DayOne.md")
-- set Shows to read theFile using delimiter return
repeat with nextLine in theFile
<text processing>
end repeat
on readFile(unixPath)
-- prepare text file to read
set foo to (open for access (POSIX file unixPath))
set txt to paragraphs of (read foo for (get eof foo)) as «class utf8»
-- set txt to paragraphs of (read foo) as «class utf8»
close access foo
return txt
end readFile
The text file looks like this:
Date: 10. Jänner 2006 20:53<br>
Tags: Hase, Muffin, Paul<br>
Location: Mühlgasse, Wiener Neudorf, Lower Austria, Austria<br>
Weather: -7° Clear<br>
1st Sign of Paul’s arrival
.... Actually it was a normal morning and as usual I got up at 6 am start preparing the breakfast.
The error occurs directly in the set txt command.
Any idea why I run into errors?
Your brackets are placed incorrectly:
set txt to paragraphs of (read foo for (get eof foo) as «class utf8»)
Otherwise you would try to convert a list into utf8.
BTW
for (get eof foo) is unnecessary.
I have a folder containing about 5000 files with names like:
Invoice 10.1 (2012) (Digital) (4-Attachments).pdf
Carbon Copy - Invoice No 02 (2010) (2 Copies) (Filed).pdf
01.Reciept #04 (Scanned-Copy).doc
I want to rename these files by removing everything from the first bracket onwards, so they look like this:
Invoice 10.1.pdf
Carbon Copy - Invoice No 02.pdf
01.Reciept #04.doc
I have found lots of scripts that will remove the last x letters, but nothing that will crop from a particular character.
Ideally I would like to use Automator, but I'm guess this might too complex for it. Any ideas?
Try:
set xxx to (choose folder)
tell application "Finder"
set yyy to every paragraph of (do shell script "ls " & POSIX path of xxx)
repeat with i from 1 to count of yyy
set theName to item i of yyy
set name of (file theName of xxx) to (do shell script "echo " & quoted form of theName & " | sed s'/ (.*)//'")
end repeat
end tell
The code posted by #adayzone will work, but there is no need to use sed for this – plain AppleScript will do, using offset:
set fullString to "Invoice 10.1 (2012) (Digital) (4-Attachments).pdf"
set trimmedString to text 1 thru ((offset of "(" in fullString) - 1) of fullString
-- trim trailing spaces
repeat while trimmedString ends with " "
set trimmedString to text 1 thru -2 of trimmedString
end repeat
this returns “Invoice 10.1". To split the file name into the name and extension, and re-add the extension, you can use System Events’ Disk-File-Folder suite, which will provide the handy name extension property you can store and re-add after trimming the name.
Assuming you use some Automator action to get the files to be processed, the full processing workflow would be to add an AppleScript action after the file selection part with the following code:
repeat with theFile in (input as list)
tell application "System Events"
set theFileAsDiskItem to disk item ((theFile as alias) as text)
set theFileExtension to name extension of theFileAsDiskItem
set fullString to name of theFileAsDiskItem
-- <insert code shown above here>
set name of theFileAsDiskItem to trimmedString & "." & theFileExtension
end tell
end repeat
If you want your Automator workflow to process the files any further, you will also have to create a list of aliases to the renamed files and return that from the AppleScript action (instead of input, which, of course, is not valid anymore).
How do I find the name of an executing AppleScript?
REASON: I want to create a script that changes its behavior based on its filename. Something like:
if myname is "Joe" then ACTION1
else if myname is "Frank" then ACTION2
else ACTION3
The normal way to get the name is by using "name of me". However applescripts are run by applescript runner so when you use that on a script you get "Applescript Runner" as the name. If you compile your script as an application then "name of me" will work. The only way to get the script name is by getting its path and extracting the name. Something like this would thus work for scripts...
getMyName()
tell me to display dialog result
on getMyName()
set myPath to path to me as text
if myPath ends with ":" then
set n to -2
else
set n to -1
end if
set AppleScript's text item delimiters to ":"
set myName to text item n of myPath
if (myName contains ".") then
set AppleScript's text item delimiters to "."
set myName to text 1 thru text item -2 of myName
end if
set AppleScript's text item delimiters to ""
return myName
end getMyName
Here's a method that works for all of the following:
*.scpt files (compiled AppleScript files; run in AppleScript Editor or with osascript)
*.applescript files (uncompiled AppleScript files; run in AppleScript Editor or with osascript)
command-line scripts that directly contain AppleScript (marked as executable and starting with #!/usr/bin/env osascript):
*.app files created with AppleScript Editor
*.app files created with Automator that contain AppleScript actions
Note: By contrast, it does not work for the following:
OS X services created with Automator that contain AppleScript actions (special *.workflow files) - always reports 'WorkflowServiceRunner[.xpc]'
general-purpose *.workflow files created with Automator that contain ApplesScript actions and that are run with automator - always reports 'Automator Runner[.app]'
Get the name of the running script, including filename extension (.scpt, .app, or .applescript, as the case may be):
tell application "System Events" to set myname to get name of (path to me)
If you want to remove the filename extension with a single command, use the following, do shell script-based approach:
tell application "System Events" to set myname to do shell script "rawName=" & quoted form of (get name of (path to me)) & "; printf '%s' \"${rawName%.*}\""
Here's an all-AppleScript alternative that is more verbose (yet concise by AppleScript standards):
tell application "System Events"
set myname to name of (path to me)
set extension to name extension of (path to me)
end tell
if length of extension > 0 then
# Make sure that `text item delimiters` has its default value here.
set myname to items 1 through -(2 + (length of extension)) of myname as text
end if
Finally, here's a variation: a subroutine that you can call with set myname to getMyName():
on getMyName()
local myName, tidSaved
tell application "System Events"
set myAlias to path to me -- alias to the file/bundle of the running script
set myName to name of myAlias -- filename with extension, if any.
if name extension of myAlias is not "" then -- strip away extension
set {tidSaved, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}}
set myName to items 1 through -(2 + (length of (get name extension of myAlias))) of myName as text
set AppleScript's text item delimiters to tidSaved
end if
end tell
return myName
end getMyName
An easier way to find out the base part of the path is using name of:
tell application "Finder"
set p to path to me
set nam to name of file p as text
end tell
Maybe this:
set appname to name of current application