在macOS中创建脱壳的POSIX路径 [英] Create a shell-escaped POSIX path in macOS

查看:159
本文介绍了在macOS中创建脱壳的POSIX路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从完整的POSIX路径(从根开始)创建一个字符串,以便可以 将其直接粘贴到诸如bash之类的Unix shell中,例如在Terminal.app中,无需在路径两边加上引号.

I need to create a string from a full POSIX path (starting at the root), so that it could be pasted directly into a Unix shell like bash, e.g. in Terminal.app, without the need for quotes around the path.

(我实际上并没有将字符串传递给shell,而是需要将其传递给另一个程序.该程序期望将路径拖放到Terminal.app中时所获得的形式.)

(I do not actually pass the string to a shell, but instead need it for passing it to another program. That program expects the path in just the form that you get when you drag a file into Terminal.app.)

为此,我需要至少在字符串中转义任何空格,方法是在它们前面加上反斜杠.还有其他一些字符.

For that, I need to escape at least any spaces in the string, by prepending them with a backslash. And some more characters as well.

例如,此路径:

/directory/-as"<>' *+

将按照以下说明进行转义:

Would be escaped as follows:

/directory/-as\"\<\>\'\ \*+

执行该转换的安全算法是什么?我可以逃避每个角色,但这太过分了.

What's a safe algorithm to perform that conversion? I could escape every character, but that would be overkill.

似乎没有框架函数可以执行此操作,因此我需要用字符串操作进行替换.

There seems to be no framework function for doing this, so I'll need to do the replacing with string operations.

为保守起见(对于最流行的外壳),同时还避免了明显的不必要的转义,应逃避哪些字符集?

To be conservative (for the most popular shells), while also avoiding clearly unnecessary escapings, what set of characters should be escaped?

推荐答案

为记录,Terminal.app在将文件名放入其窗口时转义了以下非控制ASCII字符:

For the record, Terminal.app escapes the following non-control ASCII chars when dropping a file name into its window:

空格

!"#$%&'()*,::< =>?[]`{|}〜

!"#$%&'()*,:;<=>?[]`{|}~

这些都无法逃脱:

控制代码(00-1F和7F)

Control codes (00-1F and 7F)

字母数字

+-.@ ^ _

这是执行替换的代码:

NSString* shellPathFromPOSIXPath (NSString *path)
{
    static NSRegularExpression *regex = nil;
    if (!regex) {
        NSString *pattern =
          @"([ !\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\,\\:\\;\\<\\=\\>\\?\\[\\]\\`\\{\\|\\}\\~])";
        regex =
          [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    }
    NSString *result =
      [regex stringByReplacingMatchesInString:path
                                      options:0
                                        range:NSMakeRange(0, path.length)
                                 withTemplate:@"\\\\$1"];
    return result;
}

这篇关于在macOS中创建脱壳的POSIX路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆