尝试使用applescript中的bash从剪贴板中删除多余的空格

时间:2018-06-15 16:35:49

标签: bash applescript

我正在尝试从剪贴板中的数据中删除所有格式化。

输入如下:

Name:   William R Wells
Date of Birth:  8 Dec 1942
Birth Place:    Fayette, Kentucky, USA
Mother's name:  Suda Hatton
Volume Number:  179
Certificate Number: 89145
Volume Year:    1942

我希望它看起来像这样:

Name: William R Wells, Date of Birth: 8 Dec 1942, Birth Place: Fayette, Kentucky, USA, Mother's name: Suda Hatton, Volume Number: 179, Certificate, Number: 89145, Volume Year: 1942

此脚本有效,但不会删除多余的空格,并在数据后放置逗号。

try 
    do shell script "export LC_CTYPE=UTF-8; pbpaste | fmt -w 99999 | pbcopy"        
end try
end

有什么建议吗? 谢谢 罗杰

1 个答案:

答案 0 :(得分:0)

这是一个可以完成这项工作的AppleScript。不确定这是最有效的方式,但它确实有效。

    use framework "Foundation"
    use scripting additions
    --------------------------------------------------------------------------------
    get the clipboard as text

    re_match from the result against "\t+" given replacement:" "
    re_match from the result against "[\r\n]" given replacement:", "
    re_match from the result against " +" given replacement:" "

    set the clipboard to the result
    --------------------------------------------------------------------------------
    ###HANDLERS
    on re_match against pattern from str given replacement:fmt
        set regex to current application's NSRegularExpression's ¬
            regularExpressionWithPattern:pattern ¬
                options:(current application's ¬
                NSRegularExpressionCaseInsensitive) ¬
                |error|:(missing value)

        (regex's stringByReplacingMatchesInString:str ¬
            options:0 range:{0, length of str} ¬
            withTemplate:fmt) ¬
            as text
    end re_match

下一个AppleScript更简单,更短但功能更少。但是,如果剪贴板内容的格式大致相同,则应该与上述脚本一样有效。

    set str to the clipboard as text

    set text item delimiters to {null, tab}
    set str to text items of str as text
    set the text item delimiters to {", ", linefeed, return}
    set str to text items of str as text
    set the text item delimiters to {": ", ":"}
    set str to text items of str as text

    set the clipboard to str