考虑以下两个文本文件:
def.txt
simple =
"sik", /* fill */
"trauma", /* type */
"hui", /* col */
def.dat
simple =
"sik", /* fill */
"trauma", /* type */
"hui", /* col */
以上2个文件存放在examples
目录下。
下面的 grep
命令可以正常工作:
$ grep --include=*.{txt,dat} -rnw example/ -F -e 'simple'
example/def.dat:1:simple =
example/def.txt:1:simple =
$ echo $? => 0
但是当我在C程序中执行上面的grep
命令时:
#include <stdio.h>
#include <string.h>
int main (void)
{
char cmd[1024];
strcpy (cmd, "grep --include=*.{txt,dat} -rnw example/ -F -e 'simple'");
printf ("%d\n", system (cmd));
return 0;
}
上述程序的输出是256
。
最佳答案
/bin/sh
不是 bash。 /bin/sh
不支持大括号扩展。尝试通过 /bin/sh
手动运行该命令,它也不起作用。
您的选择是手动写出命令(自己进行大括号扩展)或将命令包装在 /bin/bash -c '......'
中并确保您已经提供足够的引号转义以保持您想要的命令完整无缺(这既复杂又丑陋)。
另一种选择是根本不这样做。通过使用您执行的脚本(使用适当的 shebang 行)或(更好)为您需要解决的任务找到 native 解决方案。
关于c - C 程序中 grep 命令的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31369112/