【问题标题】:Split file by extracting lines between two keywords通过提取两个关键字之间的行来拆分文件
【发布时间】:2015-10-27 04:32:01
【问题描述】:

我有一个包含以下几行的文件:

string
string
string
MODEL 1
.
.
.
TER
string 
string
string
MODEL 2
.
.
.
TER

有 5000 个这样的MODELs。我想拆分此文件,以便将每个以 MODEL X 开头和以 TER 结尾的部分(以点显示)保存到自己的文件中,并丢弃其他所有内容。我怎样才能做到这一点?可能是awksplit

我检查了其他几个类似的问题,但未能将答案应用于我的案例。

另外请注意,我使用的是 Mac OS X。

【问题讨论】:

标签: bash awk csplit


【解决方案1】:

你可以使用这个 awk:

awk '/^MODEL/{file="model" $2} file{print > file} /^TER/{close(file); file=""}' file

工作原理:

/^MODEL/               # match lines starting with MODEL
file="model" $2        # make variable file as model + model_no from column 2
file{...}              # execute of file variable is set
{print>file}           # print each record to file
/^TER/                 # match lines starting with TER
{close(file); file=""} # close file and reset file to ""

然后验证为:

cat model1
MODEL 1
.
.
.
TER

cat model2
MODEL 2
.
.
.
TER

【讨论】:

  • 它一直工作到第 18 个文件,此时它终止并出现错误:awk: model18 makes too many open files。它还在TER 之后打印string 行。
  • 感谢您的回答,现在可以正常使用了。能否请您稍微解释一下该命令,以便我了解它是如何工作的?
  • 我在回答中添加了一些描述。
【解决方案2】:

即使dash 也可以使用:

go=false text= model_ID=
while IFS= read line; do
    if   [ "`printf "$line" | grep '^MODEL'`" ]; then
        model_ID="`printf "$line" | sed -e 's/^MODEL //'`"
        go=true
    elif [ "`printf "$line" | grep '^TER'`" ];   then
        printf "$text" > "MODEL_$model_ID"
        text=""
        model_ID=""
        go=false
    else
        $go && text="$text$line\n"
    fi
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多