I would like to run a shell command on many files that should match on a given filename regex. I found this code snippet that runs a shell command with arguments:
我想在许多文件上运行shell命令,这些文件应该与给定的文件名正则表达式匹配。我发现这个代码片段运行带有参数的shell命令:
func shell(_ arguments: [String] = []) -> String {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? "unknown"
return output
}
It runs great, but it does not resolve the parameters:
它运行良好,但它不解决参数:
shell(["ls", "~/Desktop/*.txt"])
Does not resolve the *
to all txt
files, it tries to only work on a file called *.txt
. Is there some option I need to set on Process
?
如果不解析*到所有txt文件,它会尝试仅处理名为* .txt的文件。我需要在Process上设置一些选项吗?
Thanks in advance for your help!
在此先感谢您的帮助!
1 个解决方案
#1
1
I just found out the answer! The resolving of *
and other patterns is done by the shell, Process
only runs a given command. So the solution is to create a shell and run the command in there: (will do some clean up in the code, but this works)
我刚刚找到了答案! *和其他模式的解析由shell完成,Process只运行给定的命令。因此解决方案是创建一个shell并在那里运行命令:(将在代码中进行一些清理,但这可行)
shell(["bash", "-c", "ls ~/Desktop/*.txt"])
#1
1
I just found out the answer! The resolving of *
and other patterns is done by the shell, Process
only runs a given command. So the solution is to create a shell and run the command in there: (will do some clean up in the code, but this works)
我刚刚找到了答案! *和其他模式的解析由shell完成,Process只运行给定的命令。因此解决方案是创建一个shell并在那里运行命令:(将在代码中进行一些清理,但这可行)
shell(["bash", "-c", "ls ~/Desktop/*.txt"])