从文本文件中拆分记录块

时间:2018-04-05 01:20:21

标签: linux file text awk split

大家好我有制表符分隔文件如下

输入文件

6      12312321     123213 123321       
8      afddsf      askakf  asfds          
4      fsdaofs     safjsdf kasdbfksdj        
4      safndsj     skfkds  sfsjl           
4      skjfs       akjsfk  kjdsafk        
9      asnfkjds    kjsdksd ksafnd           
7      12321321    124124 124124         
6      78787878    984929  29232       
8      afddsf      askakf  asfds           
4      fsdaofs     safjsdf kasdbfksdj        
4      safndsj     skfkds  sfsjl          
4      skjfs       akjsfk  kjdsafk          
9      asnfkjds    kjsdksd ksafn           
7      78787878    233232  242214

预期输出1:file1.txt - 根据第一列中的6和7值分割第一组

6      12312321     123213 123321       
8      afddsf      askakf  asfds          
4      fsdaofs     safjsdf kasdbfksdj        
4      safndsj     skfkds  sfsjl           
4      skjfs       akjsfk  kjdsafk        
9      asnfkjds    kjsdksd ksafnd           
7      12321321    124124 124124  

预期输出2:file2.txt

6      78787878    984929  29232       
8      afddsf      askakf  asfds           
4      fsdaofs     safjsdf kasdbfksdj        
4      safndsj     skfkds  sfsjl          
4      skjfs       akjsfk  kjdsafk          
9      asnfkjds    kjsdksd ksafn           
7      78787878    233232  242214

预期输出3:file3.txt - 基于第一列中的8和9值进行拆分

8      afddsf      askakf  asfds          
4      fsdaofs     safjsdf kasdbfksdj        
4      safndsj     skfkds  sfsjl           
4      skjfs       akjsfk  kjdsafk        
9      asnfkjds    kjsdksd ksafnd  

预期输出4:file4.txt

8      afddsf      askakf  asfds           
4      fsdaofs     safjsdf kasdbfksdj        
4      safndsj     skfkds  sfsjl          
4      skjfs       akjsfk  kjdsafk          
9      asnfkjds    kjsdksd ksafn 

1 个答案:

答案 0 :(得分:0)

这个问题很复杂,因为我们不知道如何使用正确的索引创建文件名,直到我们处理完整个文件为止。

#! /usr/bin/awk -f

BEGIN {
    FS = "\t"
    split("", b67)
    split("", b89)
    i67 = i89 = 0
}

 (i67 in b67)            { b67[i67] = b67[i67] ORS $0 }
 (i67 in b67) && $1 == 7 { ++i67 }
!(i67 in b67) && $1 == 6 { b67[i67] = $0 }

 (i89 in b89)            { b89[i89] = b89[i89] ORS $0 }
 (i89 in b89) && $1 == 9 { ++i89 }
!(i89 in b89) && $1 == 8 { b89[i89] = $0 }

END {
    f = 0
    for (i = 0; i < i67; ++i)
        print b67[i] > "file" ++f ".txt"
    for (i = 0; i < i89; ++i)
        print b89[i] > "file" ++f ".txt"
}

()模式周围in不是必需的,但希望它们增加清晰度。