2011-12-15 96 views
2

我想修改一個AppleScript,需要一個文本文件,並用文本文件中的每一行創建一個新的todo:AppleScript - 如何獲取由換行符分隔的每行剪貼板並對每行執行操作?

set myFile to (choose file with prompt "Select a file to read:") 
open for access myFile 

set fileContents to read myFile using delimiter {linefeed} 
close access myFile 

tell application "Things" 

    repeat with currentLine in reverse of fileContents 

     set newToDo to make new to do ¬ 
      with properties {name:currentLine} ¬ 
      at beginning of list "Next" 
     -- perform some other operations using newToDo 

    end repeat 

end tell 

我想不是,能夠簡單地使用剪貼板作爲數據源,所以我不必每次創建和保存文本文件,是否有任何方法來加載剪貼板,並且對於每個換行符,執行newToDo函數?

這是我迄今的嘗試,但它似乎並沒有工作,並把整個剪貼板放在一行,我似乎無法找到正確的分隔符。

try 
    set oldDelims to AppleScript's text item delimiters -- save their current state 
    set AppleScript's text item delimiters to {linefeed} -- declare new delimiters 

    set listContents to get the clipboard 
    set delimitedList to every text item of listContents 

    tell application "Things" 
     repeat with currentTodo in delimitedList 
      set newToDo to make new to do ¬ 
       with properties {name:currentTodo} ¬ 
       at beginning of list "Next" 
      -- perform some other operations using newToDo 
     end repeat 
    end tell 

    set AppleScript's text item delimiters to oldDelims -- restore them 
on error 
    set AppleScript's text item delimiters to oldDelims -- restore them in case something went wrong 
end try 

編輯: 與下面的答案的幫助下,該代碼是非常簡單!

set listContents to get the clipboard 
set delimitedList to paragraphs of listContents 

tell application "Things" 
    repeat with currentTodo in delimitedList 
     set newToDo to make new to do ¬ 
      with properties {name:currentTodo} ¬ 
      at beginning of list "Next" 
     -- perform some other operations using newToDo 
    end repeat 
end tell 

回答

3

Applescript有一個名爲「段落」的命令,它非常善於弄清楚行分隔符是什麼。正因如此,請嘗試一下。請注意,這種方法不需要「文本項目分隔符」。

set listContents to get the clipboard 
set delimitedList to paragraphs of listContents 

請注意,如果你想使用你的代碼,這是正確的方式來獲得一個換行符...

set LF to character id 10