linux - 如何根据第一列值对齐 3 个文件

标签 linux bash sorting file

我有 3 个文本文件 c.datn.dath.dat 内容类似,都是这种格式

c.dat    n.dat    h.dat
1 0.ccc  3 1.nnn  1 2.hhh
2 0.ccc  4 1.nnn  2 2.hhh
4 0.ccc  5 1.nnn  5 2.hhh

期望的输出:

1 0.ccc Inf 2.hhh
2 0.ccc Inf 2.hhh
3 Inf 1.nnn Inf
4 0.ccc 1.nnn Inf
5 Inf 1.nnn 2.hhh
6 Inf Inf Inf
7 ....

每个文件大约有 100 行,但它们并不总是从 1 开始,也不总是连续的。

我需要将这 3 个文件的第一列对齐,这样如果其他文件没有它,它就会填充诸如 NA、NaN 或 Inf 之类的内容。

谢谢!

最佳答案

awk '
{
        if(FNR==1){f++}
        a[$1,f] = $2
        if($1 > max){max = $1}
}

END{
        for(j=1;j<=max;j++){
          printf("%d\t", j)
          for(i=1;i<=f;i++){
            if(!a[j,i]){printf("Inf\t")}
            else{printf("%s\t", a[j,i])}
          }
          printf("\n")
        }
}' ./c.dat ./n.dat ./h.dat

输出

$ ./awk.dat
1       0.ccc   Inf     2.hhh
2       0.ccc   Inf     2.hhh
3       Inf     1.nnn   Inf
4       0.ccc   1.nnn   Inf
5       Inf     1.nnn   2.hhh

关于linux - 如何根据第一列值对齐 3 个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4400250/

相关文章:

git - 如何按 rc-X.Y.Z.W 形式的版本字符串顺序对 git 标签进行排序?

linux - FFMPEG。视频到图像序列,持续时间已更改

linux - 如何使 xterm 命令行像 vim 一样工作

linux - Bash 脚本在 if elif else 语句中包含逻辑与和或

linux - EOF 内的 bash 脚本无法将参数传递给函数

algorithm - 使用多个堆的 Heapsort

sorting - 是否可以只对集合进行一次排序,然后尽管 react 性仍然保持该顺序不变?

regex - 使用 egrep 和正则表达式搜索数字

python - 在 Python 中运行 bash 命令 : os vs subprocess?

bash - awk 长度计数+1