【问题标题】:How can I merge output from cat with existing file using sort command?如何使用 sort 命令将 cat 的输出与现有文件合并?
【发布时间】:2022-11-17 18:14:12
【问题描述】:

我目前有两个文件:anotherFilemyFile,它们正在合并到一个result 文件中,该文件已排序。所有这一切都是 3 个步骤,但是我希望能够做到所谓的“单线”

目前

#(script which creates 'anotherFile')
anotherFile > result
cat ./myFile | cut -f 1,2 >> result
sort -o result{,}

我希望能够“单行”这个,所以我不必参考 result 文件 3 次!

cat ./myFile | cut -f 1,2 | xargs -I sort -m anotherFile {} > finalFile

我知道上面的内容不起作用,因为 {} 不是现有文件。

【问题讨论】:

    标签: bash


    【解决方案1】:

    每个文件被引用一次:

    { ./anotherFileScript; cut -f1,2 myfile; } | sort > result
    

    【讨论】:

      【解决方案2】:

      您可以使用{} 在一个组中运行您的命令,然后通过sort 将该组的输出通过管道传输并将其重定向到一个文件中:

      {
        ./anotherFileScript
        cut -f 1,2 ./myFile
      } | sort > finalFile
      

      如果你必须把它放在一行中,你需要一些分号:

      { ./anotherFileScript; cut -f 1,2 ./myFile; } | sort > finalFile
      

      因为 cut 可以从文件中读取,所以您也可以删除不需要的 cat

      【讨论】:

      • 我会接受你的回答@Thomas,因为你是第一个。谢谢你让我觉得自己很愚蠢,也让我学到了新东西! :) 但是我应该通过邮寄方式进行更改,因为我正在使用./anotherFileScript 正在制作的文件,所以我必须使用 cat。
      • Shell 语法对人们做到了这一点;)
      猜你喜欢
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多