我如何通过使用bash读取两个文本文件来进行排列?

时间:2019-06-19 11:24:41

标签: bash

我有两个文本文件

cat A.txt

10,1,1,"ABC"
10,1,2,"ABC"
10,1,3,"baba"
10,2,1,"asd"
10,2,2,"dkkd"

cat B.txt

10,1,2,"S1"
10,2,1,"S2"
10,2,2,"S3"

我希望文件B.txt的内容应出现在与A.txt匹配的内容上方 在这里,我需要比较用逗号分隔的三个数字。如果发现相等,则说A.txt的(10,1,2)和B.txt的(10,1,2) 我如何获得此输出并使用bash保存到另一个文件

10,1,1,"ABC"
10,1,2,"S1"
10,1,2,"ABC"
10,1,3,"baba"
10,2,1,"S2"
10,2,1,"asd"
10,2,2,"S3"
10,2,2,"dkkd"

1 个答案:

答案 0 :(得分:3)

只需使用前三个字段对文件进行排序。因为您更喜欢B.txt前面的A.txt行,所以我使用了-s, --stable选项来禁用最后一种排序,希望sort选择它读取的第一行。因此,通过将第一个文件指定为B.txt,我希望它将B.txt行放在前面。

sort -s -t, -k1,3 B.txt A.txt

将输出:

10,1,1,"ABC"
10,1,2,"S1"
10,1,2,"ABC"
10,1,3,"baba"
10,2,1,"S2"
10,2,1,"asd"
10,2,2,"S3"
10,2,2,"dkkd"