【问题标题】:merge contents of two files into one file in bash在bash中将两个文件的内容合并为一个文件
【发布时间】:2015-02-25 17:41:29
【问题描述】:

我有两个包含以下内容的文件

文件1

Line1file1
Line2file1
line3file1
line4file1

文件2

Line1file2
Line2file2
line3file2
line4file2

我想将这些文件的内容合并到 file3 中

文件3

Line1file1
Line1file2
Line2file1
Line2file2
line3file1
line3file2
line4file1
line4file2

如何在 bash 中连续合并一个文件和另一个文件中的文件?

谢谢

【问题讨论】:

    标签: linux bash awk sed merge


    【解决方案1】:

    您始终可以使用paste 命令。

    paste -d"\n" File1 File2 > File3
    

    【讨论】:

      【解决方案2】:
      $ cat file1
      Line1file1
      Line2file1
      line3file1
      line4file1
      
      $ cat file2
      Line1file2
      Line2file2
      line3file2
      line4file2
      
      $ paste -d '\n' file1 file2 > file3
      
      $ cat file3
      Line1file1
      Line1file2
      Line2file1
      Line2file2
      line3file1
      line3file2
      line4file1
      line4file2
      

      【讨论】:

        【解决方案3】:

        paste 是解决此问题的方法,但如果您需要添加额外条件或不想在一个文件的行数多于另一个文件时以空行结束,则此替代方法可能是一种有用的方法或其他任何使它成为更复杂问题的东西:

        $ awk -v OFS='\t' '{print FNR, NR, $0}' file1 file2 | sort -n | cut -f3-
        Line1file1
        Line1file2
        Line2file1
        Line2file2
        line3file1
        line3file2
        line4file1
        line4file2
        

        【讨论】:

        • 获取输出需要什么,例如: Line1file1 line3file1 Line1file2 line3file2 Line2file1 line4file1 Line2file2 line4file2(并排)
        • 请发布一个新的后续问题,不要在 cmets 中提出后续问题。
        【解决方案4】:

        在 Linux 中:

        grep -En '.?' File1 File2 | sed -r 's/^[^:]+:([^:]+):(.*)$/\1 \2/g' \
            | sort -n | cut -d' ' -f2- > File3
        

        如果您使用的是 OS X,请使用 -E 而不是 -r 作为 sed 命令。思路是这样的:

        1. 使用grep 为每个文件的行编号。
        2. 使用sed 删除文件名并将行号放入以空格分隔的列中。
        3. 使用sort -n按行号排序,既稳定又保持文件顺序。
        4. 删除带有cut 的行号并重定向到文件。

        编辑:使用paste 更简单,但如果您的一个文件比另一个文件长,则会产生空行,此方法只会继续处理较长文件中的行。

        【讨论】:

          【解决方案5】:
          while read line1 && read -u 3 line2
          do 
              printf "$line1\n" >> File3
              printf "$line2\n" >> File3
          done < File1 3<File2
          

          您可以使用文件描述符,从两个文件中读取并将每一行打印到输出文件。

          【讨论】:

          • 这只是附加文件,他想要每个文件的交替行
          • 如果文件包含 printf 格式字符(例如%s),它还将从每行中去除前导和尾随空格并扩展转义序列并产生语法错误和/或其他不良行为,并且将痛苦的缓慢。这只是另一个例子,说明为什么在处理文本时在 shell 中编写循环总是错误的方法。
          猜你喜欢
          • 2020-03-16
          • 2012-05-31
          • 2013-09-06
          • 2011-03-27
          • 2017-09-06
          • 1970-01-01
          • 1970-01-01
          • 2021-08-13
          • 1970-01-01
          相关资源
          最近更新 更多