简体   繁体   English

C程序中grep命令的异常行为

[英]Unexpected behavior of grep command in C program

Consider the following two text files: 考虑以下两个文本文件:

def.txt

simple =
"sik", /* fill */
"trauma", /* type */
"hui", /* col */

def.dat

simple =
"sik", /* fill */
"trauma", /* type */
"hui", /* col */

The above 2 files are stored in examples directory. 以上2个文件存储在examples目录中。

The following grep command works fine as expected: 以下grep命令可以正常运行:

$ grep --include=*.{txt,dat} -rnw example/ -F -e 'simple'
example/def.dat:1:simple =
example/def.txt:1:simple =
$ echo $? => 0

But when I execute the above grep command in C program: 但是当我在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;
}

The output of the above program is 256 . 上面的程序的输出为256

/bin/sh is not bash. /bin/sh不是bash。 /bin/sh does not support brace expansions. /bin/sh不支持大括号扩展。 Try running that command through /bin/sh manually and it won't work either. 尝试通过/bin/sh手动运行该命令,该命令也不起作用。

Your choices are to write out the command manually (do the brace expansion yourself) or wrap your command in /bin/bash -c '......' and ensure you've provided enough quote escaping to keep your desired command intact that way (which is complicated and ugly). 您的选择是手动写出命令(自行进行大括号扩展)或将命令包装在/bin/bash -c '......'并确保提供了足够的引号转义以使所需命令完整无缺这样(复杂又丑陋)。

The other option is to not do this at all. 另一个选择是根本不执行此操作。 Either by using a script that you execute (with an appropriate shebang line) or (better) by finding native solutions to the task you need to solve. 通过使用执行的脚本(带有适当的shebang行)或(更好的)通过找到需要解决的任务的本机解决方案来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM