【问题标题】:How to sort lines in textfile according to a second textfile如何根据第二个文本文件对文本文件中的行进行排序
【发布时间】:2016-07-31 19:26:49
【问题描述】:

我有两个文本文件。

文件 A.txt:

john
peter
mary
alex
cloey

文件 B.txt

peter does something
cloey looks at him
franz is the new here
mary sleeps

我愿意

  • 合并两者
  • 根据另一个文件对一个文件进行排序
  • 将 B 的未知行放在末尾​​li>

像这样:

john
peter does something
mary sleeps
alex
cloey looks at him
franz is the new here

【问题讨论】:

  • 你试过什么?

标签: linux sorting vim text awk


【解决方案1】:
$ awk '
    NR==FNR { b[$1]=$0; next }
    { print ($1 in b ? b[$1] : $1); delete b[$1] }
    END { for (i in b) print b[i] }
  ' fileB fileA
john
peter does something
mary sleeps
alex
cloey looks at him
franz is the new here

上面将以“随机”顺序打印 fileB 中的剩余项目(有关详细信息,请参阅http://www.gnu.org/software/gawk/manual/gawk.html#Scanning-an-Array)。如果这是一个问题,请编辑您的问题,以阐明您对需要打印的顺序的要求。

它还假设每个文件中的键都是唯一的(例如,peter 在每个文件中只作为键值出现一次)。如果不是这种情况,请再次编辑您的问题,以包括一个键在您的充足输入/输出中多次出现的情况,并另外说明您希望如何处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-15
    • 2020-04-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2011-10-15
    相关资源
    最近更新 更多