【问题标题】:how to use AWK to merge two columns from each of 10 files如何使用 AWK 合并 10 个文件中的每一个的两列
【发布时间】:2013-09-23 19:25:48
【问题描述】:

我有 10 个文件具有相同的制表符分隔的列结构。我需要合并每个文件的第 8 列和第 9 列。我想出了以下 AWK 代码,但它一次只合并两个文件。我正在寻求同时合并所有 10 个文件的帮助,我不确定这是否可行。

我所有的文件名都遵循相同的模式(s1s2.txt、s3s4.txt、s5s6.txt、....s19s20.txt)

#!/bin/bash

awk '
 BEGIN {
        #load array with contents of the first file
        while ( getline < "s1s2.txt" > 0)
         {
           s1s2_counter++
           f1_8[s1s2_counter] = $8
           f1_9[s1s2_counter] = $9
         }
}
   {OFS="\t"}

   { #output the columns 8 and 9 from the first file before the second file
    print f1_8[NR],f1_9[NR], $8, $9
   } ' s3s4.txt

【问题讨论】:

    标签: awk merge


    【解决方案1】:
    awk -F'\t' '{a[FNR] = a[FNR] (NR==FNR?"":FS) $8 FS $9} END{for (i=1;i<=FNR;i++) print a[i]}' s1s2.txt .... s19s20.txt
    

    使用 getline 通常是错误的方法,请参阅http://awk.info/?tip/getline

    【讨论】:

    • 不客气。如果/当您对此或您得到的任何其他答案感到满意时,请记住单击该答案旁边的复选标记,这样其他人就不会浪费时间试图为您提出替代方案。
    • @user2228325 在 SO,您通过支持/接受他的回答来表示感谢。如果它解决了您的问题,请不要忘记这样做。
    猜你喜欢
    • 2020-07-07
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2016-07-30
    相关资源
    最近更新 更多