【问题标题】:Combine columns from different files合并来自不同文件的列
【发布时间】:2011-12-06 00:05:45
【问题描述】:

我有两个具有以下结构的文本文件:

文件 1

Column1:Column2
Column1:Column2
...

文件 2

Column3
Column3
...

我想创建一个具有这种文件结构的文件:

Column1:Column3
Column1:Column3
...

欢迎任何建议,但如果解决方案可以通过 Bash shell 或 sed / awk / perl / etc...

完成,那就太好了

【问题讨论】:

    标签: perl bash sed awk


    【解决方案1】:
    cut -d: -f1 "File 1" | paste -d: - "File 2"
    

    这会从文件 1 中剪切字段 1(由冒号分隔)并将其与文件 2 中的唯一列一起粘贴,用冒号分隔输出字段。

    【讨论】:

      【解决方案2】:

      这是一个 awk 解决方案。它假定 file1 和 file2 的行数相等。

      awk -F : '{ printf "%s:",$1; getline < "file2"; print }' < file1
      

      【讨论】:

        【解决方案3】:

        由于没有建议使用纯 bash 实现,还假设行数相同(仅限 bash v4):

        mapfile -t file2 < file2
        
        index=0
        while IFS=: read -r column1 _; do
                echo "$column1:${file2[index]}"
                ((index++))
        done < file1
        

        bash v3:

        IFS=$'\n' read -r -d '' file2 < file2
        
        index=0
        while IFS=: read -r column1 _; do
                echo "$column1:${file2[index]}"
                ((index++))
        done < file1
        

        【讨论】:

          猜你喜欢
          • 2017-09-02
          • 1970-01-01
          • 1970-01-01
          • 2016-12-09
          • 1970-01-01
          • 2020-11-30
          • 2022-08-18
          • 1970-01-01
          相关资源
          最近更新 更多