c - 将 sed 的输出(从 grep 传送)重定向到 C 程序中的文件

标签 c sed pipe

我使用以下命令将 sed 的输出重定向到 tmp 文件:

grep --include=*.txt -A 3 -rnw abx/ -F -e 'simple' | sed -n 's#.*/\([^/]*\.txt\).*"\([^"]*\)*"[[:space:]]*,[[:space:]]*/\*[[:space:]]*col[[:space:]]*\*/#\1\n\2#p' > tmp

如果在终端中使用输出,则输出将在 tmp 中重定向,但在 C 程序中,不会向“tmp”写入任何内容。

C 程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()  {
  char cmd[1028];

   strcpy (cmd, "grep --include=*.txt -A 3 -rnw abx/ -F -e 'simple' | sed -u -n 's#.*/\\([^/]*\\.txt\\).*\"\\([^\"]*\\)*\"[[:space:]]*,[[:space:]]*/\\*[[:space:]]*col[[:space:]]*\\*/#\\1\\n\\2#p' > tmp");

  system (cmd);
  return 0;
}

编辑: 示例文本文件:

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

该文件存储在abx/中。

最佳答案

您可能需要对正则表达式中的“\”进行“双重转义”。

([^/]*\\.txt\\) --> ([^/*\\\\.txt\\\\)

因为 C 在构建字符串时会将“\\”更改为“\”,并且我认为 cmd 也会将“\\”更改为“\”。

关于c - 将 sed 的输出(从 grep 传送)重定向到 C 程序中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366549/

相关文章:

C 中的冲突类型和转换

c - Powerpc arch 上的 gcc 内联汇编程序隐式函数声明

c++ - 如何执行管道隐藏C++

c# - 用 C 重写 GetHashCode32(string s) 方法

c - 在每个函数的开头应用断点

xml - sed one-liner - 查找关键字周围的定界符对

linux - 将匹配模式的第一个字母大写

linux - sed 在两个模式之间提取文本,其中第二个模式可以是其中之一

Linux 管道示例。 ipc管道创建

bash - 解释 bash/pipe 表达式中的最后一个破折号