使用awk将不同文件中的列复制到单个文件中

时间:2018-12-05 09:28:56

标签: bash awk

我大约有500多个文件,其中有两列“ Gene short name”和“ FPKM”值。行数是相同的,并且“ Gene short name”列在所有文件中都是公用的。我想通过将第一列保留为基因短名称(可以从任何文件中获取)并保留其他具有FPKM的列来创建矩阵。

我已经使用了该命令,但是效果很好,但是如何将其用于500个文件?

 paste -d' ' <(awk -F'\t' '{print $1}' 69_genes.fpkm.txt) \
            <(awk -F'\t' '{print $2}' 69_genes.fpkm.txt) \
            <(awk -F'\t' '{print $2}' 72_genes.fpkm.txt) \
            <(awk -F'\t' '{print $2}' 75_genes.fpkm.txt) \
            <(awk -F'\t' '{print $2}' 78_genes.fpkm.txt) > col.txt

样本数据(文件用制表符分隔):

head 69_genes.fpkm.txt 
gene_short_name FPKM
        DDX11L1 0.196141
        MIR1302-2HG 0.532631
        MIR1302-2   0
        WASH7P  4.51437

预期结果

gene_short_name FPKM FPKM FPKM FPKM
DDX11L1 0.196141 0.206591 0.0201256 0.363618
MIR1302-2HG 0.532631 0.0930007 0.0775838 0
MIR1302-2 0 0 0 0
WASH7P 4.51437 3.31073 3.23326 1.05673
MIR6859-1 0 0 0 0
FAM138A 0.505155 0.121703 0.105235 0
OR4G4P 0.0536387 0 0 0
OR4G11P 0 0 0 0
OR4F5 0.0390888 0.0586067 0 0

此外,我想将名称“ FPKM”更改为“ filename_FPKM”。

2 个答案:

答案 0 :(得分:1)

提供输入

$ cat a.txt
a       1
b       2
c       3
$ cat b.txt
a       I
b       II
c       III
$ cat c.txt
a       one
b       two
c       three

您可以循环:

cut -f1 a.txt > result.txt
for f in a.txt b.txt c.txt
do
  cut -f2 "$f" | paste result.txt - > tmp.txt
  mv {tmp,result}.txt
done
$ cat result.txt
a       1       I       one
b       2       II      two
c       3       III     three

答案 1 :(得分:0)

在awk中,为了清楚起见,使用@Micha的数据:

$ awk '  
BEGIN { FS=OFS="\t" }    # set the field separators
FNR==1 {
    $2=FILENAME "_" $2   # on first record of each file rename $2
}
NR==FNR {                # process the first file
    a[FNR]=$0            # hash whole record to a
    next
}
{                        # process other files
    a[FNR]=a[FNR] OFS $2 # add $2 to the end of the record
}
END {                    # in the end
    for(i=1;i<=FNR;i++)  # print all records
        print a[i]
}' a.txt b.txt c.txt

输出:

a       a.txt_1 b.txt_I c.txt_one
b       2       II      two
c       3       III     three