sed:1:" ' / regex / ...":无效的命令代码'

时间:2016-10-19 05:07:38

标签: bash go sed bsd

我试图编写一个程序来自动组装和运行sed命令。我使用以下代码段生成命令:

switch command {
case "=", "d":
    return fmt.Sprintf("'/%s/ %s'", regex, command)
case "c", "a", "i":
    return fmt.Sprintf("'/%s/ %s\\\n%s'", regex, command, phrase)
case "s", "y":
    return fmt.Sprintf("'%s/%s/%s/'", command, regex, phrase)
default:
    return ""
}

然后我使用以下代码片段来运行完整命令:

fmt.Println("Running command: sed", args)
program := exec.Command(programName, args...)
output, err := program.CombinedOutput()
fmt.Printf("%s", output)
if err != nil {
    fmt.Println(err)
}

这导致以下输出(生成100个命令,这只是1):

Running command: sed [-e '/([0a-z][a-z0-9]*,)+/ c\
abc said he""llo!!!\n    1  ' -e '/(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)/ a\
0,0,0,156, aac' -e '/(s?)a.b,a\nb/ d' -f number_lines.txt -f eliminate_punctuation.txt -f delete_leading_trailing_whitespace.txt -f delete_last_ten_lines.txt -f eliminate_blanks.txt -f number_non_blank_lines.txt -f reverse_lines.txt -f strip.txt input1.txt input2.txt input3.txt]

sed: 1: " '/([0a-z][a-z0-9]*,)+/ ...": invalid command code '
exit status 1

这很奇怪,但是如果我手工运行生成的命令(当然没有方括号),那么奇怪的是,它的工作正常!这里发生了什么?

1 个答案:

答案 0 :(得分:1)

Shell剥离引号字符,exec.Command没有。因此sed可能会通过命令传递'。尝试使用单引号形成命令:

switch command {
// remove single quotes from strings
case "=", "d":
    return fmt.Sprintf("/%s/ %s", regex, command)
case "c", "a", "i":
    return fmt.Sprintf("/%s/ %s\\\n%s", regex, command, phrase)
case "s", "y":
    return fmt.Sprintf("%s/%s/%s/", command, regex, phrase)
default:
    return ""
}