【问题标题】:Bash script to split file into two files while changing output file during processing在处理期间更改输出文件时将文件拆分为两个文件的 Bash 脚本
【发布时间】:2014-12-31 01:07:44
【问题描述】:

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

//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

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

【问题讨论】:

  • fedorqui,谢谢你清理我的帖子

标签: bash shell unix


【解决方案1】:

这可以通过awk来完成:

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

说明

这会将行输出到文件f,当找到taco 或burrito 时,文件的名称会发生​​变化:

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

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

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

【讨论】:

    【解决方案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]。

    【讨论】:

    • 是的,再次阅读问题后,我认为我误解了要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2015-05-20
    • 2017-12-04
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多