Bash按文件将文件拆分为流

时间:2015-11-14 06:38:30

标签: regex bash sed

我想拆分文件,例如:

#define MACRO "exists"

code *code(code code, code code_code) {
  code more_code;
  return more_code;
}

#define THING

// etc

分为两个流,我可以在重新组合之前使用其他实用程序进行操作 - 也就是说,根据具有特定命令的模式修改某些行,以及使用不同命令将模式匹配的行。

我想这需要使用命名管道。

我当前的方法读取文件两次,并使用grep过滤行:

FILE="example.txt"
grep '^#' < "$FILE" | cpp -P > combined.txt
grep -v '^#' < "$FILE" | awk '{ print $4 }' >> combined.txt

有没有办法使用sed或其他实用程序按模式拆分文件?

1 个答案:

答案 0 :(得分:1)

您可以浏览一次文件,对匹配或不匹配的行执行不同的操作:

awk '/^#/ {system("echo \"=== "$0"\"")}
    !/^#/ {system("echo \"+++ "$0"\"")}
    ' example.txt

为每一行调用系统会产生大量开销,因此请尝试使用awk函数。

编辑: 我不明白为什么文件在两个流中都是plit,cpp想要解析一个完整的文件。 echo '#define MACRO "exists"'|cpp -P是。 还有你的时候

#ifdef NOTVALID
ignore these lines
#endif

我认为cpp需要看第二行 我试着打电话给

awk -v q=\' 'BEGIN {FS=" ";} /^#/ {cmd="echo "q$0q"|cpp -P"; system(cmd)}
        !/^#/ {system("echo \"+++ "$0"\"")}
        ' example.txt

但这对你没有用。

使用其他实用程序时,也许可以排除^#行:

sed '/^[^#]/ s/e/===replaced the first e in the line by this line===/' example.txt