如何打开文本文件并使用文件中的文本重命名?

时间:2014-02-08 18:42:19

标签: applescript

我正在尝试使用文件文本中的字符串使用applescript重命名一些文本文件。这些文件是旧的usenet消息,最终出现了严重混乱的名称,如REARIY-1。我已经想出了如何读取文件并找到我想要的文本字符串(它由SUBJECT继续)我还想出了如果我在文本中有用户类型的情况下如何重命名文件,但是我在打开时遇到了问题要读取它的文件,还要获取允许我重命名的路径。

到目前为止,我所做的最好的是以下内容(要求用户注意两次选择相同的文件):

set foo to choose file with multiple selections allowed

set fileAlias to foo as alias

set footext to read file ((choose file with prompt "phhhht") as string)

set targetText to "Subject:"
set extractedProperty to ""
set foundIt to "Target text not found."



set oldDelims to AppleScript's text item delimiters
try
set AppleScript's text item delimiters to {ASCII character 13}
set bar to text items of footext
repeat with thisItem in bar

    if thisItem contains targetText then
        set foundIt to thisItem
        exit repeat
    end if
end repeat
set AppleScript's text item delimiters to oldDelims
on error
set AppleScript's text item delimiters to oldDelims
end try

try
if thisItem contains "not found" then
    display dialog "text not found, filename not changed"
    tell me to quit
end if
end try

repeat with thisWord in words of foundIt
if contents of thisWord is not targetText then
    set extractedProperty to extractedProperty & thisWord & " "
end if
end repeat

set extractedProperty to characters 9 thru -2 of extractedProperty as text

display dialog extractedProperty -- for check only

tell application "Finder"
set name of fileAlias to (extractedProperty & ".txt")
end tell

2 个答案:

答案 0 :(得分:0)

您只需要更改第三行:

set foo to choose file with multiple selections allowed
set fileAlias to foo as alias
set footext to read file ((choose file with prompt "phhhht") as string)

set footext to read file (foo as string)

答案 1 :(得分:0)

你可以尝试这样的事情。

    set fileList to choose file with multiple selections allowed

set targetText to "Subject:"
set targetTextCount to count of characters in targetText
set extractedProperty to ""

repeat with thisItem in fileList
    set footext to paragraphs of (read file (thisItem as string))

    repeat with this_item in footext
        if this_item contains targetText then

            set extractedProperty to characters from ((offset of targetText in this_item) + targetTextCount) to -1 of this_item as string

            --log extractedProperty
            tell application "Finder"
                set name of (thisItem as alias) to (extractedProperty & ".txt")
            end tell
            exit repeat
        end if
    end repeat
end repeat