0

嗨,我有一个文本文件 sample.txt 作为

    =====record1
    title:javabook
    price:$120
    author:john
    path:d:
    =====record2
    title:.netbook
    author:paul
    path:f:
    =====record3
    author:john
    title:phpbook
    subject:php
    path:f:
    price:$150
    =====record4
    title:phpbook
    subject:php
    path:f:
    price:$150

从这里我想根据作者拆分数据,它应该分成2个文件,其中包含

test1.txt

=====record1
    title:javabook
    price:$120
    author:john
    path:d:
=====record3
    author:john
    title:phpbook
    subject:php
    path:f:
    price:$150

test2.txt

=====record2
    title:.netbook
    author:paul
    path:f:

像上面一样,我想根据作者字段动态地将主 sample.txt 文件分类为子文件,请建议我一种方法。

4

1 回答 1

1

试试这一行:

awk -F: '{a[++i]=$0;if(i==3)f=$2}i==4{for(x=1;x<=i;x++)print a[x]>f".txt";i=0}' file

此行将使用作者的姓名命名输出文件。如果名称有空格,则必须引用它。如果你需要一个编号的文本文件,也很简单,只需在读取行期间创建一个数组。就像是:

f['John']=1
f['Tom']=2
f['Jerry']=3
...

这条线只是展示它是如何工作的。

以您的内容file为例:

kent$  awk -F: '{a[++i]=$0;if(i==3)f=$2}i==4{for(x=1;x<=i;x++)print a[x]>f".txt";i=0}' file

kent$  head *.txt
==> john.txt <==
=====record1
title:javabook
author:john
path:d:
=====record3
title:javabook
author:john
path:f:

==> paul.txt <==
=====record2
title:.netbook
author:paul
path:f:
于 2013-06-03T14:12:59.027 回答