c - C 程序中 grep 命令的意外行为

标签 c grep

考虑以下两个文本文件:

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/

相关文章:

c - memcpy 删除 C 中 char 数组中的变量

c++ - float 比较给出不同的结果

python - 使用 Python 在非常大的文件中查找字节序列

linux - 如何使用 grep 只获取一行的一部分

linux - shell 脚本 : Using grep and tr in the shebang

regex - grep 用于在特定位置的特定行中包含特定文本的文件

c - 将二进制读入字符串c

c - 从文件中读取整数并将其保存到数组中

c - printf中的类型检查是如何实现的?

linux - 从 bash 脚本中的文本文件验证帐户创建