awk将特定的行转置到列并将它们分组

  • 本文关键字:转置 awk linux bash shell awk
  • 更新时间 :
  • 英文 :


我在stdout中有以下数据:

09:13:32 19.2 cpu(1)
09:13:32 15.6 cpu(2)
09:13:32 16.7 cpu(3)
09:13:32 17.1 cpu(6)
09:13:32 17.1 cpu(7)
09:13:32 16.9 cpu(8)
09:13:32 16.7 cpu(9)
09:13:39 13.0 cpu(1)
09:13:39 9.2 cpu(2)
09:13:39 9.1 cpu(3)
09:13:39 7.1 cpu(6)
09:13:39 27.1 cpu(7)
09:13:39 46.9 cpu(8)
09:13:39 36.7 cpu(9)

尝试将其转换为如下内容

['Time', 'cpu(1)', 'cpu(2)', 'cpu(3)', 'cpu(6)', 'cpu(7)', 'cpu(8)', 'cpu(9)'],
['09:13:32',  19.2, 15.6, 16.7, 17.1, 17.1, 16.9, 16.7],
['09:13:39', 13.0, 9.2, 9.1, 7.1, 27.1, 46.9, 36.7]

换句话说,我需要原始数据与Google可视化折线图格式对齐,如下所示:https://developers.google.com/chart/interactive/docs/gallery/linechart

我正在尝试使用awk来实现这一点,并且需要一些输入。

awk '{ for(N=1; N<=NF; N+=2) print $N, $(N+1); }' | awk 'BEGIN{q="47"; printf "["q"Time"q","q"CPU"q"],"}/master/{q="47"; printf "["q$10q"," $3"],"}' | sed 's/,$//'"

注意:我可以像下面这样更改原始数据列

Time CPU(%) CPU Number

CPU(%) CPU Number Time

使用任意次数和任意数量的cpu,并且即使您没有数据一段时间+cpu组合也可以工作,只要输入不是太大以至于无法全部装入内存:

$ cat tst.awk
BEGIN {
OFS = ", "
}
!seenTimes[$1]++ {
times[++numTimes] = $1
}
!seenCpus[$3]++ {
cpus[++numCpus] = $3
}
{
vals[$1,$3] = $2
}
END {
printf "[47%s47%s", "Time", OFS
for ( cpuNr=1; cpuNr<=numCpus; cpuNr++ ) {
cpu = cpus[cpuNr]
printf "47%s47%s", cpu, (cpuNr<numCpus ? OFS : "]")
}
for ( timeNr=1; timeNr<=numTimes; timeNr++ ) {
time = times[timeNr]
printf ",%s[47%s47%s", ORS, time, OFS
for ( cpuNr=1; cpuNr<=numCpus; cpuNr++ ) {
cpu = cpus[cpuNr]
val = vals[time,cpu]
printf "%s%s", val, (cpuNr<numCpus ? OFS : "]")
}
}
print ""
}

$ awk -f tst.awk file
['Time', 'cpu(1)', 'cpu(2)', 'cpu(3)', 'cpu(6)', 'cpu(7)', 'cpu(8)', 'cpu(9)'],
['09:13:32', 19.2, 15.6, 16.7, 17.1, 17.1, 16.9, 16.7],
['09:13:39', 13.0, 9.2, 9.1, 7.1, 27.1, 46.9, 36.7]

相关内容

  • 没有找到相关文章

最新更新