1

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

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

那里有 5000 个这样MODEL的 s。我想拆分这个文件,以便每个部分的开头MODEL X和结尾TER(用点显示)都保存到自己的文件中,而其他所有内容都被丢弃。我怎样才能做到这一点?可能与awkor split

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

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

4

2 回答 2

2

您可以为此使用 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
于 2015-08-04T17:05:43.233 回答
1

这甚至适用于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
于 2015-08-04T17:06:45.950 回答