将文本片段移动到文档末尾

时间:2016-02-23 14:21:24

标签: grep applescript textwrangler

我正在将一本XML格式的书转换成EPUB。它有67章和1000多个脚注。我发现在Epub中创建脚注的好方法是将注释的内容移动到末尾的列表中,并在注释调用者和结尾处的元素之间来回链接。我在Textwrangler中使用Grep搜索将标签更改为正确的html标签。但是,我想不出一种方法来使用Grep查找文本片段并将其移动到文档的末尾?有没有其他简单的方法来使用Textwrangler或其他文本编辑器?我假设Applescript可以与Textwrangler链接为我做(我使用OS X),但我不知道如何。我不是程序员,所以我更喜欢尽可能简单的解决方案,只要不是手动剪切和粘贴:)

1 个答案:

答案 0 :(得分:1)

此脚本使用grep模式查找字符串并将其附加到文档末尾的新行

tell application "TextWrangler"
    tell text of window 1
        set cL to count lines
        select first line -- to start at the top
        repeat
            -- start from the selection, selection change when the "find" command found the search pattern in the document
            set r to find "[\\d]+" options {search mode:grep} with selecting match -- change "[\\d]+" to your search pattern 
            if found of r then
                if startLine of found object of r > cL then exit repeat -- the end of the original document, to not search in the appended lines
                set contents of found object of r to "" -- delete the found text
                make line with data found text of r -- append a new line + the found text
            else
                exit repeat
            end if
        end repeat
    end tell
end tell

重要:在AppleScript脚本中,您必须转义模式中的反斜杠。

示例:AppleScript中 TextWrangler 的此模式[\d]*\t必须为[\\d]*\\t

更新以解决另一个问题。

此脚本搜索<li id="......",如果它不唯一,则添加后缀 - &gt; - 和整数。

set uniq_ID_names to {}
tell application "TextWrangler"
    tell text of window 1
        select first line -- to start at the top
        repeat
            -- start from the selection, selection change when the "find" command found the search pattern in the document
            set r to find "<li id=\"[^\"]+" options {search mode:grep} with selecting match -- get character from <li id=" until the next double quote character
            if not found of r then exit repeat
            set t to found text of r
            if t is in uniq_ID_names then -- same ID's name
                set i to 1
                repeat -- add suffix to the found text
                    set t2 to t & "-" & i
                    if t2 is not in uniq_ID_names then
                        add suffix (found object of r) suffix ("-" & i)
                        set t to t2
                        exit repeat
                    end if
                    set i to i + 1
                end repeat
            end if
            set end of uniq_ID_names to t
        end repeat
    end tell
end tell
相关问题