【问题标题】:Merge 2nd line of txt files together将第二行 txt 文件合并在一起
【发布时间】:2019-03-07 19:06:46
【问题描述】:

我有几百个 txt 文件,每个文件 2 行。

要合并它们,我通常会这样做:

cat *.txt > final.txt

但是,我只需要对每个文件的第二行执行此操作,因此最终输出类似于

2nd line of 1st file
2nd line of 2nd file
2nd line of 3rd file
(and so on..)

有什么想法可以做到这一点吗?

【问题讨论】:

  • awk 'NR==2' file 将打印文件的第二行

标签: bash awk cat


【解决方案1】:

第一个解决方案:您能否尝试使用 GNU awknextfile 是 GNU awk 中非常好的选项,当条件满足时,它将跳过当前 Input_file 中的所有行。

awk 'FNR==2{print;nextfile}' *.txt > output_file


第二个解决方案:如果你没有 GNU awk 试试。在这里,因为我们假设awk 中没有nextfile,所以我在每个文件的第二行创建一个flag,当它为TRUE 时,只需转到下一行/跳过它们并尝试保存某个时间。注意这个标志值也会在每个文件的第一行被重置。

awk 'FNR==1{flag=""} FNR==2{print;flag=1} flag{next}'  *.txt > output_file


第三种解决方案:在这里也添加whilefind 方法,使用headtail。 AFAIK 头部和尾部不应读取整个文件。

while read line
do
  head -n +2 "$line" | tail -1 
done <  <(find -type f -name "*.txt") > "output_file"

【讨论】:

    【解决方案2】:

    使用 GNU sed:

    sed -n -s 2p *.txt > final.txt
    

    sed -s '2!d' *.txt > final.txt
    

    来自man sed

    -s:将文件视为单独的而不是单个连续的长流。

    【讨论】:

    • -s 已添加到注释中:)
    【解决方案3】:
    find . -name "*.txt" -type f -exec awk 'NR==2' {} \;
    

    【讨论】:

      【解决方案4】:

      使用awk

      awk 'FNR == 2 { print; nextfile }' *.txt > final.txt
      

      FNR 包含当前文件中的行号。当它在第 2 行时,它将打印该行,然后转到下一个文件。

      【讨论】:

      • 嗨 Barmar 先生,既然您是 bash 专家,请您检查我的第三个(while+find)答案,如果这在速度等方面有好处,请提供您的意见一样。
      • 这是可以接受的,只是非常冗长并且运行了很多进程。
      • 感谢您的意见,不胜感激。
      【解决方案5】:

      使用 Perl

       perl -ne ' if($.==2) { print ; close(ARGV) } ' *.txt
      

      带有示例文件

      $ cat allison1.txt
      line1 in file1
      line2 in file1
      
      $ cat allison2.txt
      line1 in file2
      line2 in file2
      
      $ cat allison3.txt
      line1 in file3
      line2 in file3
      
      $  perl -ne ' if($.==2) { print ; close(ARGV) } ' allison*txt
      line2 in file1
      line2 in file2
      line2 in file3
      
      $
      

      【讨论】:

        猜你喜欢
        • 2016-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        • 1970-01-01
        相关资源
        最近更新 更多