doufu6423 2019-06-11 15:27
浏览 74
已采纳

错误执行命令,其中包含奇怪的字符

I'm trying to call the builtin function find to print out the contents of all the text files in a subfolder my-files. I understand that there are easier ways to do this, but I need to get it working with exec. I suspect that exec is not handling quotes correctly. My initial code is as follows:

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))

This works fine and prints out

Output is...
my-files/goodbye.txt
my-files/badfile.java
my-files/hello.txt

However, when I then try to start adding 'weirder' characters, it falls apart. If I change the first line to

fullCmd := "find my-files -maxdepth 1 -type f -iname \"*.txt\""

Nothing prints out. Worse, if I change the line to:

fullCmd := "find my-files -maxdepth 1 -type f -exec cat {} \\;"

Find errors out with this stdout:

Output is...
find: -exec: no terminating ";" or "+"

I thought I was correctly escaping the neccesary characters, but I guess not. Any ideas on how to get the command to work? For reference, this command does exactly what I want when entered directly on the command line:

find my-files -maxdepth 1 -type f -iname "*.txt" -exec cat {} \;
  • 写回答

1条回答 默认 最新

  • dongyue7796 2019-06-11 15:31
    关注

    It has nothing to do with "weird" characters. \"*.txt\"" is quoted for your shell, but you're not running this in your shell. It should just be *.txt, which is the actual argument you want find to receive as the value for -iname:

    fullCmd := "find my-files -maxdepth 1 -type f -iname *.txt"
    

    Though, because this is not a shell, I would strongly recommend against this approach of building a shell-like command as a single string and splitting on spaces; just provide the args as an array in the first place to avoid confusion like this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制