AppleScript:如何将文件夹的路径名存储到数组中,并用“\”替换空格?

AppleScript:如何将文件夹的路径名存储到数组中,并用“\”替换空格?

我有一个文件夹,文件夹里面有一堆子文件夹。我希望使用 AppleScript 将这些子文件夹的路径名存储到一个数组中。

这是我的问题:每个包含“  ”(空格)的路径名,我都想用包含 UNIX 友好的“ ”符号(反斜杠后跟一个空格;如/my/fancy\ path/)的路径名替换。

如您所见,我在这里只完成了一半的目标。我花了一个晚上的时间,费尽心机地尝试,摆弄replace_chars子程序、do shell script组合sed,还有谁知道什么。毫无进展。

tell application "Finder"

    set myRepos to name of folders of folder ("/Users/hced/Dropbox/GitHub/" as POSIX file)
    --> {"320andup", "Baseline.js (jQuery & vanilla JS version)", "Bootstrap (HTML, CSS, and JS toolkit from Twitter)", "Chirp.js (Tweets on your website, simply)", "Coordino"}

end tell

编辑:有效路径示例为/Users/hced/Dropbox/GitHub/A\ folder\ named\ with\ spaces

答案1

阅读您的问题,我不确定您是否可以使用带引号的路径名而不是转义空格......

tell application "Finder"
        set folderGitHub to folder ("/Users/hced/Dropbox/GitHub/" as POSIX file)

        set listFolders to (every folder in folderGitHub as alias list)
end tell

set listPosixPathsQuoted to {}

repeat with aliasFolder in listFolders
        set listPosixPathsQuoted to listPosixPathsQuoted & {quoted form of POSIX path of aliasFolder}
end repeat

答案2

这应该可以做到:

tell application "Finder"
    set myRepos to name of folders of folder ("/Users/hced/Dropbox/GitHub/" as POSIX file)
end tell

repeat with theIndex from 1 to number of items in myRepos
    set item theIndex in myRepos to replace_chars(item theIndex in myRepos, " ", "\\ ")
end repeat

return myRepos

on replace_chars(this_text, search_string, replacement_string)
    set AppleScript's text item delimiters to the search_string
    set the item_list to every text item of this_text
    set AppleScript's text item delimiters to the replacement_string
    set this_text to the item_list as string
    set AppleScript's text item delimiters to ""
    return this_text
end replace_chars

这将获取您已经获得的文件夹名称,并循环遍历列表中的每个项目,将每个空格字符替换为\。请注意,反斜杠需要转义,并且 AppleScript 编辑器会将字符串显示为包含双反斜杠。但是,您可以通过执行并将结果文本粘贴到文本编辑器中来验证它们是否已使用单个反斜杠正确转义set the clipboard to item 2 of myRepos- 这只是 AppleScript 编辑器的一个怪癖。

replace_chars函数是一个相当标准的样板。我复制了它来自 Mac OS X 自动化

答案3

Trash Man 的管理员发布于麦金塔将转义所有问题字符...

set myFolder to quoted form of "/Users/hced/Dropbox/GitHub/"

    set theFolders to every paragraph of (do shell script "find " & myFolder & " -type d -depth 1 ")
    set escFolders to {}

    repeat with aFolder in theFolders
        set end of escFolders to escape_string(aFolder as text)
    end repeat

    on escape_string(input_string)
    set output_string to ""
    set escapable_characters to " !#^$%&*?()={}[]'`~|;<>\"\\"
    repeat with chr in input_string
        if (escapable_characters contains chr) then
            set output_string to output_string & "\\" -- This actually adds ONE \ to the string.
        else if (chr is equal to "/") then
            set output_string to output_string & ":" -- Swap file system delimiters
        end if
        set output_string to output_string & chr
    end repeat
    return output_string as text
end escape_string

相关内容