Bash脚本在处理过程中更改输出文件时将文件拆分为两个文件

时间:2014-12-30 16:18:01

标签: bash shell unix

我正在尝试将文本文件拆分为两个不同的文件,文件看起来像这样:

//ABC12//burrito (line of text)
(line of text)
(line of text)
etc
//ABC12//taco (line of text)
(line of text)
(line of text)
etc
//ABC12//taco (line of text)
(line of text)
(line of text)
etc
//ABC12//burrito (line of text)
(line of text)
(line of text)
etc

所以我想将以burrito开头的所有行和所有后续行分成一个名为burrito的文件,直到读出一条带有taco的行,我认为最好的方法是:

for each line in $text;
   if line contains burrito
         outputfile=burrito
         line>>$outputfile
   elseif line contains taco
         outputfile=taco
         line>>$outputfile
   else
         line>>$outputfile

但我不确定,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

可以使用awk

完成此操作
awk '/burrito/ {f="burrito"} /taco/ {f="taco"} {print > f}' file

解释

这会将行输出到文件f,其名称会在找到tacoburrito时更改:

  • /burrito/ {f="burrito"}这意味着:如果该行包含burrito,则将变量f设置为burrito
  • /taco/ {f="taco"}taco相同。
  • {print> f} prints the line into the file stored in f . You can also say {print> f“.txt”}`或其他东西。

如果您要设置默认文件名,以便在找到burritotaco之前将其输出到其他位置,您可以说:

awk 'BEGIN {f="another_file"} /burrito/ {f="burrito"} /taco/ {f="taco"} {print > f}' file

答案 1 :(得分:2)

您可以使用此awk命令:

wk 'BEGIN{split("burrito taco", a); f=a[1]} {
   for (i=1; i<=length(a); i++) if ($0 ~ a[i]) f=a[i]; print $0 > f}' file
  • 这会将包含taco的所有行重定向到名为taco
  • 的输出文件
  • 这会将包含burrito的所有行重定向到名为burrito
  • 的输出文件
  • 您可以将输出文件名初始化为其他内容而不是f=a[1]