【问题标题】:NSTask calling perl and piping in find not workingNSTask 调用 perl 和管道在 find 中不起作用
【发布时间】:2014-07-16 06:56:04
【问题描述】:

我正在尝试在目录中的一堆文件上运行 perl 正则表达式一行(通过递归查找),并且在让 NSTask 执行一行在命令行中执行的操作时遇到了一些麻烦。

终端中的 perl 单行程序可以工作,并且通过 shell 将命令作为字符串运行的简化 NSTask 也可以工作。

Perl 命令(有效)

perl -p -i -e 's/DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";/DEBUG_INFORMATION_FORMAT = \"dwarf\";/g' `find . -name *.pbxproj`

简单的 NSTask(有效)

使用Inket's answer from another question

NSString *command = @"perl -p -i -e 's/DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";/DEBUG_INFORMATION_FORMAT = \"dwarf\";/g' `find /Users/nflacco/Projects/XXX/XXX.xcodeproj -name *.pbxproj`";

NSTask* task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
[task setArguments:@[@"-c", command]];
[task launch];

Xcode 终端应用(不工作)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSString *workspacePath = @"/Users/nflacco/Projects/XXX/XXX.xcodeproj";

        NSString *old = @"DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";";
        NSString *new = @"DEBUG_INFORMATION_FORMAT = \"dwarf\";";

        NSTask *task = [[NSTask alloc] init];
        [task setLaunchPath:@"/usr/bin/perl"];
        NSString *regex = [NSString stringWithFormat:@"'s/%@/%@/g'", old, new];
        NSString *pathArg = [NSString stringWithFormat:@"`find %@ -name *.pbxproj`", workspacePath];
        [task setArguments:@[ @"-p", @"-i", @"-e", regex, pathArg]];
        [task launch];

    }
    return 0;
}

Xcode 控制台:

Can't open `find /Users/nflacco/Projects/XXX/XXX.xcodeproj -name *.pbxproj`: No such file or directory.
Program ended with exit code: 0

【问题讨论】:

    标签: objective-c xcode foundation nstask


    【解决方案1】:

    您必须按照您的第一个代码示例调用/bin/sh。这是因为使用了 `,它是一个 shell 表达式来执行子 shell 并回显其输出。

    因此:

    NSString *workspacePath = @"/Users/nflacco/Projects/XXX/XXX.xcodeproj";
    
    NSString *old = @"DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";";
    NSString *new = @"DEBUG_INFORMATION_FORMAT = \"dwarf\";";
    
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/sh"];
    NSString *regex = [NSString stringWithFormat:@"'s/%@/%@/g'", old, new];
    NSString *pathArg = [NSString stringWithFormat:@"`find %@ -name *.pbxproj`", workspacePath];
    [task setArguments:@[ @"/usr/bin/perl", @"-p", @"-i", @"-e", regex, pathArg]];
    [task launch];
    

    最好还是在您的应用中完成所有这些工作...

    【讨论】:

    • 我正在编写一个插件来切换各种 Xcode 项目设置(更改设置可以使构建时间缩短 60%)。否则,我只需将脚本签入项目 repo。
    猜你喜欢
    • 2019-12-19
    • 2016-02-18
    • 2015-06-02
    • 1970-01-01
    • 2018-02-02
    • 2017-05-28
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多