linux - 如何根据第二个文本文件对txt文件中的行进行排序

标签 linux sorting vim text awk

我有两个文本文件。

文件A.txt:

john
peter
mary
alex
cloey

文件B.txt

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

我愿意

  • 合并两者
  • 根据一个文件对另一个文件进行排序
  • 把B的未知行放在最后

像这样:

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

最佳答案

$ 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

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

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

关于linux - 如何根据第二个文本文件对txt文件中的行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535059/

相关文章:

Vim 复制具有相同光标位置的内容

c++ - 调用存储在映射中的模板化 std::function

windows - 不能在 gvim (windows) 中将 CTRL-<Space> 与 Cscope 插件一起使用

python - 如何正确设置 Vim 自动缩进以编辑 Python 文件?

c++ - 这两个功能可以合二为一吗?

algorithm - 找到一种时间复杂度为 O(n + k*log(k)) 的整数排序算法

php - 在 PHP 中从数据库中按字母顺序排序

linux - 搜索多个 php 文件,并替换文本?

c - 如何将参数注入(inject)scanf?

linux - 如何在 Redhat Linux 中修复 TPM? RedHat Linux 安装后第一次启动挂起