Applescript做shell来创建带文本和操作的文件

时间:2015-07-06 10:54:47

标签: shell applescript

我正在尝试使用Applescript编写一个简单的记录器。我有几个问题

首先我测试文件是否存在,如果不存在我想创建一个具有该名称的文件并将第一行设置为字符串“Counter:0”。

到目前为止,我有这个,但我的语法错了。感谢任何帮助,因为网上的信息有点苗条。

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

其次我想读取文件的第一行(即Counter:0)并在:by 1之后递增整数。

帮助v.much赞赏

2 个答案:

答案 0 :(得分:0)

根据vadian的回答:

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

优点是这不会忽略错误。它还可以找到您的主目录,而无需您在代码中手动输入它。这是安全的,因为我们首先检查logFolder。如果该文件夹存在,则其余代码不会失败。我知道AppleScript有一个检查文件是否存在的方法,但是我发现在处理POSIX路径时这些功能相当难以使​​用,所以我使用的是do shell脚本,它自然会处理POSIX路径。

答案 1 :(得分:-1)

请尝试此操作,更改第一行中的文件路径(考虑尾部斜杠)

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