【问题标题】:Execute a command using popen使用 popen 执行命令
【发布时间】:2013-11-24 18:39:03
【问题描述】:

我有一个 C++ 程序,我想在其中执行以下命令:

cmd = "(diff <(perl -ne 's/^\\S+\\s//; if ((/aaa/ .. /bbb/) && /ccc/)"
            " { print \"$_\"}' file1)"
            "<(perl -ne 's/^\\S+\\s//; if ((/aaa/ .. /bbb/) && /ccc/)"
            " { print \"$_\"} file2)) ";

当我想执行这个命令时出现这个错误:

Search pattern not terminated at -e line 1.

我注意到以下命令的工作方式如下:

cmd = "diff <(echo aa) <(echo bb)"
string strCall = "bash -c \"( " + cmd + " ) 2>&1\"";
stream = popen(strCall.c_str(),"r"); // doesn't work popen(**str**.c_str(),"r")

一个包含 '"' 的示例 perl 命令的工作方式如下:

cmd = "perl -ne '{print \"$1\"}' file"
stream = popen(str.c_str(),"r"); // doesn't work  popen(**strCall**.c_str(),"r");

但如果 perl 命令不包含 '"',它可以双向工作:

cmd = "perl -ne '{print $1}' file"
string strCall = "bash -c \"( " + cmd + " ) 2>&1\"";
stream = popen(str.c_str(),"r"); // also works popen(**strCall**.c_str(),"r");

如何在同一命令中同时使用 diff 和 perl。我假设我必须使用 strCall。 我也尝试过像这样逃避 perl cmd,但它不起作用:

cmd = "perl -ne '{print \\\"$1\\\"}' file" // one '/' for '/', one for "'" and one for '"'.

这也不起作用,但是我不允许使用 R("str"):

cmd = R"(perl -ne '{print \"$1\"}' file)"
string strCall = "bash -c \"( " + cmd + " ) 2>&1\"";
stream = popen(strCall.c_str(),"r")

谢谢。

【问题讨论】:

  • 不确定是否是换位错误,但看起来您可能在第二个 perl 子 shell 上缺少关闭单引号。我假设你有这个在命令行上工作?
  • 在 cmd 中工作。这是一个换位错误。

标签: c++ perl diff popen


【解决方案1】:

我知道我没有回答你的问题,但是一旦你达到这么多引用级别,一个常见的解决方案是编写一个简单的 shell 脚本,然后从 popen 调用它。

例如,popen("/path/diffscript.sh", "r");

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多