我使用以下命令将 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/