2012-04-11 43 views
0

在此先感謝您的意見。我有一個關於下面的AppleScript的問題。我運行同一個命令兩次,得到兩個不同的響應。首先是一個unix命令(grep)和第二個純AppleScript。我正在嘗試在teX文檔中找到一個字符串,即\ begin {document}。我想在AppleScript之前添加一個\ usepackage {whatever}。我有一個python腳本,它做我想做的事,除了我不能將活動窗口的文件位置從TeXShop傳遞到python,只有AppleScript。純AppleScript和Unix有不同的結果

問題:爲什麼unix版本與純AppleScript版本不同?請記住\ begin {document}在我正在檢查的文檔中是絕對的。純版本正常工作。

tell application "TeXShop" 
    -- get the front document and save 
    set thisDoc to the front document 
    -- get the filename and cursor position of the document 
    get path of thisDoc 
    set filePath to result 
    --set insPoint to offset of selection of thisDoc 
end tell 
set searchResult to do shell script "grep -q \\begin{document}" & filePath & "; echo $?" --echo 0 on match found/success and 1 on not found 
if searchResult = "0" then 
    display dialog "string found" 
else 
    display dialog "string not found" 
end if 
set findThis to "\\begin{document}" 
set theFileContent to read filePath 
if result contains findThis then 
    display dialog "string found" 
else 
    display dialog "string not found" 
end if 
+0

這將是更容易,如果你格式化你的AppleScript代碼,以幫助。 – jahroy 2012-04-11 19:16:33

+0

@ macmadness86「當您決定哪個答案對您最有幫助時,請通過單擊答案左側的複選框大綱將其標記爲接受的答案。」 – adayzdone 2012-04-14 11:48:28

回答

1

shell解釋特殊字符,在這種情況下,這兩個反斜槓和大括號;和grep和AppleScript本身也解釋反斜槓。

set searchResult to do shell script "grep -q '\\\\begin{document}'" & filePath & "; echo $?" 

單引號保護大括號並防止shell解析反斜槓;你需要4個反斜槓,因爲AppleScript每個吃一個(出於同樣的原因,你需要在純AppleScript版本中使用兩個反斜槓)並且grep吃另一個(反斜槓的意思是「將下一個字符視爲文字」,GNU grep除外, 「把下一個角色看作特殊的」,但這不會發生在這裏)。

0

如果你正在運行

grep \begin{document} <file> 

那麼它不工作是因爲反斜槓在shell特殊字符。嘗試:

grep \\begin{document} <file> 
0

我有一個python腳本,它做我想要的,除了我不能將活動窗口的文件位置從TeXShop傳遞到python,只有AppleScript。

但是你可以使用AppleScript的獲取當前打開的.tex文件的路徑,然後用do shell script通過該路徑作爲參數傳遞給你的Python腳本。事情是這樣的(經測試,工程進展順利,如果你的Python腳本接受作爲命令行參數文件路徑):

property thePythonScript : "/Users/user/path/to/script.py " 
tell application "TeXShop" 
    set thisDoc to the front document 
    set filePath to (path of thisDoc) 
    do shell script ("'" & thePythonScript & "' " & quoted form of filePath)  
end tell