【问题标题】:How can I combine one file's tail with another's head?如何将一个文件的尾部与另一个文件的头部结合起来?
【发布时间】:2019-02-05 21:58:39
【问题描述】:

我知道如何从 .t​​xt 数据中获取例如前 2 行并将其附加到 .txt 数据的末尾。但是我应该如何将 .txt 数据的最后 2 行添加到 .txt 数据的第 1 行

我试过了:

tail -n 2 test1.txt >> head test1.txt # takes last 2 lines of text and adding 
                                      it to the head 

看起来非常错误,但我在任何地方都找不到答案,用尾巴和头来做。

tail n 2 test1.txt >> head test1.txt
cat test1.txt

请有人更正我的代码,以便我得到预期的结果。

【问题讨论】:

  • 你可以这样做:(tail -n 2 test1.txt && cat test1.txt) >> test.tmp.txt && mv test.tmp.txt test1.txt
  • 标题不应该只描述问题是关于什么的,而应该描述问题本身,这样其他人就可以判断它的答案是否会是对自己的问题有帮助。我试图为此进行编辑。

标签: linux shell


【解决方案1】:

只需一个接一个地运行这两个命令 - 这样做产生的标准输出将与您通过将它们的输出连接在一起得到的结果完全相同,而无需执行显式/额外的连接步骤:

tail -n 2 test1.txt
head -n 1 test1.txt

如果要将它们的输出重定向在一起,请将它们放在大括号中:

{
  tail -n 2 test1.txt
  head -n 1 test1.txt
} >out.txt

【讨论】:

    【解决方案2】:

    怎么样:

    $ cat file1.txt 
    file 1 line 1
    file 1 line 2
    file 1 line 3
    file 1 line 4
    $ cat file2.txt 
    file 2 line 1
    file 2 line 2
    file 2 line 3
    file 2 line 4
    $ tail -n 2 file1.txt > output.txt
    $ head -n 1 file2.txt >> output.txt 
    $ cat output.txt 
    file 1 line 3
    file 1 line 4
    file 2 line 1
    

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 2021-08-06
      • 1970-01-01
      • 2011-08-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      相关资源
      最近更新 更多