файл копируется в определенную папку и переименовывается в x.txt. Как мне открыть x.txt и вставить «X:» - PullRequest
1 голос
/ 30 сентября 2011

РЕДАКТИРОВАТЬ: regulus6633 сделал сценарий, который намного лучше, чем мой план ниже, он отлично работает, если ваш файл шаблона не полностью пуст (я думаю, что это первоначально вызвало ошибку).Спасибо!

Этот скрипт должен (1) скопировать x.txt в определенную папку, переименовать его в new_name, (2) открыть его, (3) вставить «new_name» во все заглавные буквы и (4) вставьте ":" с последующим возвратом и возвратом.Первая часть работает, но у меня возникают проблемы с выяснением (2), (3) и (4).Код, который я написал до сих пор, вставлен ниже.

 tell application "Finder"
        display dialog "new_name_dialogue" default answer " "
        set new_name to (text returned of result)
        set Selected_Finder_Item to (folder of the front window) as text
        duplicate file "Q:x:7:n7:GTD scripting:template folder:x.txt" to "Q:X:7:SI:SIAG1"
        set Path_Of_X to "Q:X:7:SI:SIAG1:" & "x.txt" as string
        set name of file Path_Of_X to (new_name as text) & ".txt"
#[something that let's me open the file is needed here]
#[something that pastes "new_name" & ":" in ALL CAPS]
#[something that inserts two lineshifts]
    end tell

Ответы [ 2 ]

1 голос
/ 30 сентября 2011

В общем, поскольку вы имеете дело с TXT-файлом, вам не нужно «открывать» файл в приложении и вставлять текст. Мы можем читать и писать в текстовые файлы прямо из applecript. Таким образом, мы читаем текст из файла шаблона, добавляем к нему любой текст, который хотим, а затем записываем новый текст в новый файл. Если вы хотите открыть и просмотреть новый файл, вы можете сделать это после. Я сделал это в разделе «TextEdit» кода.

Вы можете увидеть в конце скрипта, у меня есть подпрограммы для написания текстового файла, а также для изменения имени файла на CAPS. Поэтому попробуйте следующее ...

-- initial variables
set templateFile to "Q:x:7:n7:GTD scripting:template folder:x.txt"
set copyFolder to "Q:X:7:SI:SIAG1:" -- notice this path ends in ":" because it's a folder

-- get the new name
display dialog "new_name_dialogue" default answer ""
set newName to (text returned of result)
set newPath to copyFolder & newName

-- get the text of the template file
set templateText to read file templateFile

-- add the file name in CAPS, a colon, and 2 returns at the beginning of templateText
set capsName to upperCase(newName)
set newText to capsName & ":" & return & return & templateText

-- write the newText to newPath
writeTo(newPath, newText, text, false)

-- open the new file in textedit
tell application "TextEdit" to open file newPath



(*============== SUBROUTINES ==============*)
on writeTo(targetFile, theData, dataType, apendData)
    -- targetFile is the path to the file you want to write
    -- theData is the data you want in the file.
    -- dataType is the data type of theData and it can be text, list, record etc.
    -- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
    try
        set targetFile to targetFile as text
        if targetFile does not contain ":" then set targetFile to POSIX file targetFile as text
        set openFile to open for access file targetFile with write permission
        if apendData is false then set eof of openFile to 0
        write theData to openFile starting at eof as dataType
        close access openFile
        return true
    on error
        try
            close access file targetFile
        end try
        return false
    end try
end writeTo

on upperCase(theText)
    set chrIDs to id of theText
    set a to {}
    repeat with i from 1 to (count of chrIDs)
        set chrID to item i of chrIDs
        if chrID ≥ 97 and chrID ≤ 122 then set chrID to (chrID - 32)
        set end of a to chrID
    end repeat
    return string id a
end upperCase
0 голосов
/ 30 сентября 2011

здесь нужно что-то, что позволяет мне открыть файл

tell application "TextEdit" to open Path_Of_X

что-то, что вставляется new_name во ВСЕ КОПИИ

Существует действительно хорошее стороннее дополнение для сценариев ( Satimage OSAX ), которое вы можете использовать для подобных вещей (это будет работать, только если вы скачали дополнение для сценариев) ...

set UPPER_CASE to uppercase new_name & ":"

то, что вставляет два сдвига строки

return & return
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...