我正在尝试调用内置函数find
,以打印出子文件夹my-files中所有文本文件的内容。我知道可以使用更简单的方法来执行此操作,但是我需要使其与exec一起使用。我怀疑exec无法正确处理报价。我的初始代码如下:
fullCmd := "find my-files -maxdepth 1 -type f"
cmdParts := strings.Split(fullCmd, " ")
output, _ := exec.Command(cmdParts[0], cmdParts[1:]...).CombinedOutput()
fmt.Println("Output is...")
fmt.Println(string(output))
这可以正常工作并打印出来
Output is...
my-files/goodbye.txt
my-files/badfile.java
my-files/hello.txt
但是,当我然后尝试开始添加“奇怪”字符时,它就会崩溃。如果我将第一行更改为
fullCmd := "find my-files -maxdepth 1 -type f -iname \"*.txt\""
什么都不会打印出来。更糟糕的是,如果我将行更改为:
fullCmd := "find my-files -maxdepth 1 -type f -exec cat {} \\;"
使用此标准输出查找错误:
Output is...
find: -exec: no terminating ";" or "+"
我以为我正确地转义了必要的字符,但我想不是。关于如何使命令起作用的任何想法?作为参考,当直接在命令行中输入以下命令时,该命令完全可以实现我想要的功能:
find my-files -maxdepth 1 -type f -iname "*.txt" -exec cat {} \;
答案 0 :(得分:7)
与“怪异”字符无关。 \"*.txt\""
为您的shell引用,但您没有在shell中运行它。它应该只是*.txt
,它是您希望find
作为-iname
的值接收的实际参数:
fullCmd := "find my-files -maxdepth 1 -type f -iname *.txt"
尽管,因为这不是 外壳程序,所以我强烈建议不要将类似外壳程序的命令构建为单个字符串并在空格上分割的方法;只是首先将args作为数组提供,以避免像这样的混乱。