gpt4 book ai didi

matrix - 使用 awk 从表中创建矩阵

转载 作者:行者123 更新时间:2023-12-02 17:57:46 25 4
gpt4 key购买 nike

我想使用这个表:

a   16  moe max us
b 11 tom mic us
d 14 roe fox au
t 29 ann teo au
n 28 joe joe ca

并使用 awk(或 bash 中的任何其他简单选项)创建此矩阵:

    a_16;   b_11;   d_14;   t_29;   n_28
us; moe_max; tom_mic; ; ;
au; ; ; roe_fox; ann_teo;
ca; ; ; ; ; joe_joe

我尝试了这个,但没有成功:

awk '{a[$5]=a[$5]?a[$5] FS $1"_"$2:$1"_"$2; b[$5]=b[$5]?b[$5] FS $3"_"$4:$3"_"$4;} END{for (i in a){print i"\t" a[i] "\t" b[i];}}' fis.txt

最佳答案

使用任何awk

$ cat tst.awk
{
row = $NF
col = $1 "_" $2
vals[row,col] = $3 "_" $4
}

!seenRow[row]++ { rows[++numRows] = row }
!seenCol[col]++ { cols[++numCols] = col }

END {
OFS = "; "

printf " "
for ( colNr=1; colNr<=numCols; colNr++ ) {
col = cols[colNr]
printf "%s%s", col, (colNr<numCols ? OFS : ORS)
}

for ( rowNr=1; rowNr<=numRows; rowNr++ ) {
row = rows[rowNr]
printf "%s%s", row, OFS
for ( colNr=1; colNr<=numCols; colNr++ ) {
col = cols[colNr]
#val = ((row,col) in vals ? vals[row,col] : " ")
val = vals[row,col]
printf "%s%s", val, (colNr<numCols ? OFS : ORS)
}
}
}

$ awk -f tst.awk file
a_16; b_11; d_14; t_29; n_28
us; moe_max; tom_mic; ; ;
au; ; ; roe_fox; ann_teo;
ca; ; ; ; ; joe_joe

在你的问题中,我看不到预期输出中的模式,即每个 ; 后面应该有 1、2、3 或 4 个空格; 所以我只是在多于。按摩它以适应。

关于matrix - 使用 awk 从表中创建矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75266518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com