【问题标题】:extract multiple columns from multiple files with bash, awk or sed使用 bash、awk 或 sed 从多个文件中提取多个列
【发布时间】:2012-08-13 14:51:07
【问题描述】:

我正在尝试从两个不同目录的文本文件中提取 column1 和 column7。这些目录中的文件名相同。我需要将输出保存到另一个目录。

file1.txt in D1 directory

column1  column2  column3  column7
david    45.2       14.6   45.0
grecy    12.0       0.0    12.0
anjal    23.2       321.0  34.5

file1.txt in D2 directory

column1  column2  column3  column7
david    45.2       14.6   56.0
grecy    10.0       0.0    12.0
moha     23.1       321.0  334.5

output format (save the output as file1.txt in D3 directory)

column1  column1  column7  column7
david      david    45.0   56.0
grecy      grecy    12.0   12.0
anjal      moha     34.5   334.5

您的建议将不胜感激。

【问题讨论】:

    标签: bash sed awk


    【解决方案1】:
    awk '{
         a1=$1;b1=$4;
         getline <"D2/file1.txt";
         print a1,$1,b1,$4
    }' D1/file1.txt >D3/file1.txt
    

    【讨论】:

      【解决方案2】:

      使用paste 和awk 的快捷方式:

      paste D1/file1.txt D2/file1.txt | awk '{ printf "%s\t%s\t%s\t%s\n", $1, $5, $4, $8 }' > D3/file1.txt
      

      结果:

      column1 column1 column7 column7
      david   david   45.0    56.0
      grecy   grecy   12.0    12.0
      anjal   moha    34.5    334.5
      

      编辑:要处理多个文件,您可以使用 bash 循环:

      for i in D1/*.txt; do paste "$i" D2/${i/D1\//} | awk '{ printf "%s\t%s\t%s\t%s\n", $1, $5, $4, $8 }' > D3/${i/D1\//}; done
      

      【讨论】:

      • 感谢您的回答。您的代码仅适用于单个文件。能否提供多个文件的代码?
      • @user1606106:我已经更新了处理多个文件的答案。 HTH。
      【解决方案3】:
      join -j 1 -o 1.1,2.1,1.7,2.7 <(D1/file1.txt | sort -k1,1) <(sort -k1,1 D2/file1.txt) > D3/file1.txt
      

      【讨论】:

        猜你喜欢
        • 2012-06-09
        • 2012-05-12
        • 1970-01-01
        • 2013-01-07
        • 2021-07-24
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多