【问题标题】:Join a specific column for several files and preserve file name as column name加入多个文件的特定列并将文件名保留为列名
【发布时间】:2020-04-21 17:26:36
【问题描述】:

我正在尝试合并一些制表符分隔的文件:

File_A.tsv

probeId   BetaVal    Annot
  a         1         X
  b         2         Y
  c         3         Z

File_B.tsv

probeId   BetaVal    Annot
  a         4         X
  b         5         Y
  c         6         Z

File_C.tsv

probeId   BetaVal    Annot
  a         7         X
  b         8         Y
  c         9         Z

如何按 BetaVal 列合并这些文件并将文件名稳定为列名(同时获得制表符分隔文件)?

probeId  File_A.tsv   File_B.tsv   File_C.tsv   Annot
  a           1           4             7         X
  b           2           5             8         Y
  c           3           6             9         Z

我正在尝试类似:

for file in *;
do
join -j 1 File_A file;
done

但这是不正确的。此外,我不确定如何将文件名写为列名。

【问题讨论】:

  • 您好 Jeni,请说明您如何确定列标题应为 A、B 和 C?但我不会 join 会为你这样做......
  • 文件中是否有前导空格或制表符以及尾随换行符,如图所示?
  • 我不确定如何确定标题。实际上,标题可以是文件名(我已经编辑了问题)
  • 如果所有 CSV 文件中的行数不同怎么办?
  • 您保留最后一列?或者,您是否假设所有文件中的最后一列都相同?

标签: bash awk sed


【解决方案1】:

你可以使用这个gnu awk:

awk -v OFS='\t' '{
   a[$1][ARGIND] = (FNR==1?FILENAME:$2)
   b[$1] = $3
}
END {
   for (i in a) {
      printf "%s", i
      for(j in a[i])
         printf "%s%s", OFS, a[i][j]
      print OFS b[i]
   }
}' File_[ABC].tsv | column -t

probeId  File_A.tsv  File_B.tsv  File_C.tsv  Annot
a        1           4           7           X
b        2           5           8           Y
c        3           6           9           Z

【讨论】:

    【解决方案2】:
    echo -e "\nprobeId  File_A.tsv   File_B.tsv   File_C.tsv   Annot";\
    join -o 1.1 1.2 2.2 2.3 -1 1 -2 1 File_A.tsv File_B.tsv|\
    join -o 1.1 1.2 1.3 2.2 1.4 -1 1 -2 1 - File_C.tsv |\
    awk '{printf(" %-8s %-12s %-12s %-12s %s\n", $1,$2,$3,$4,$5);}'|tail +2
    
    probeId  File_A.tsv   File_B.tsv   File_C.tsv   Annot
     a        1            4            7            X
     b        2            5            8            Y
     c        3            6            9            Z
    

    我假设第一列是关键字段,我试图猜测 您的想法,但最好阅读这些链接 进一步了解join

    https://linuxconfig.org/learning-linux-commands-join

    https://landoflinux.com/linux_join_command.html

    join multiple files

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2017-04-13
      • 1970-01-01
      • 2020-09-14
      • 2017-04-21
      相关资源
      最近更新 更多