合并基于某些条件
问题描述:
我有两个文件,如下两个管道分隔的文件合并成一个文件| F2 | C3 | D3 | E3
A4 | F2 | 4 | 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 | 4 | 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 | 4 | D4 | E4
Z3 | F2 | C3 | D3 | E3
Z4 | F2 | 4 | D4 | E4
Z5 | F3 | C5 | d5 | e5
a5 | f4 | c5 | d5 | e5
我尝试将File2附加到File1,然后如此rt在第二场。但它不会维护源文件中的订单。
答
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:通过添加示例来编辑答案。 – sameerkn