【问题标题】:Merge two pipe separated files into one file based on some condition根据某些条件将两个管道分隔的文件合并为一个文件
【发布时间】:2017-03-09 11:58:36
【问题描述】:

我有两个文件如下: 文件 1:
a1|f1|c1|d1|e1
a2|f1|c2|d2|e2
a3|f2|c3|d3|e3
a4|f2|c4|d4|e4
a5|f4|c5|d5|e5

文件2:
z1|f1|c1|d1|e1
z2|f1|c2|d2|e2
z3|f2|c3|d3|e3
z4|f2|c4|d4|e4
z5|f3|c5|d5|e5

输出文件应该有两个文件交错的行,以便根据第二个字段对行进行排序。
输出文件:
a1|f1|c1|d1|e1
a2|f1|c2|d2|e2
z1|f1|c1|d1|e1
z2|f1|c2|d2|e2
a3|f2|c3|d3|e3
a4|f2|c4|d4|e4
z3|f2|c3|d3|e3
z4|f2|c4|d4|e4
z5|f3|c5|d5|e5
a5|f4|c5|d5|e5

我尝试将 File2 附加到 File1,然后对第二个字段进行排序。但它不保持源文件中存在的顺序。

【问题讨论】:

    标签: sorting unix merge pipe csv


    【解决方案1】:
    file_1:
    a1|f1|c1|d1|e1
    a2|f1|c2|d2|e2
    a3|f2|c3|d3|e3
    a4|f2|c4|d4|e4
    a5|f4|c5|d5|e5
    
    file_2:
    z1|f1|c1|d1|e1
    z2|f1|c2|d2|e2
    z3|f2|c3|d3|e3
    z4|f2|c4|d4|e4
    z5|f3|c5|d5|e5
    
    
    awk -F"|" '{a[$2] = a[$2]"\n"$0;} END {for (var in a) print a[var]}' file_1 file_2  | sed '/^\s*$/d'
    
    • awk

      -F    : tokenize the data on '|' character.
      a[$2] : creates an hash table whose key is string identified by $2 and 
              value is previous data at a[$2] + current complete line ($0) separated by newline.
      
    • sed

      used to remove the empty lines from the output.
      
      
      Output:
      a1|f1|c1|d1|e1
      a2|f1|c2|d2|e2
      z1|f1|c1|d1|e1
      z2|f1|c2|d2|e2
      a3|f2|c3|d3|e3
      a4|f2|c4|d4|e4
      z3|f2|c3|d3|e3
      z4|f2|c4|d4|e4
      z5|f3|c5|d5|e5
      a5|f4|c5|d5|e5
      

    【讨论】:

    • 谢谢,@sameerkn。我得到了所需的合并文件,但它没有根据第二个字段按字母顺序排序。
    • @BalkrushnaChaudhary:通过包含一个示例来编辑答案。
    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 2012-07-04
    • 2011-05-03
    • 2019-05-15
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2020-07-15
    相关资源
    最近更新 更多