gpt4 book ai didi

linux - 在 AWK 中 `rec=rec","$i` 没有按预期工作,其中 $i 是记录中的每个字段

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:37 26 4
gpt4 key购买 nike

我在 linux 机器上有我的 vmstat 输出:

# cat vmstat.out
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 2675664 653028 3489156 0 0 1 19 22 7 5 1 94 0 0

我打算将每个字段下的值以逗号分隔的格式与时间戳一起保存(当然是将其用作 CSV 文件,以便稍后传输到我们非常喜欢的 MS Excel)。所以基本上这就是我想要的:

预期输出:

2016,05,19,23,53,58,1,0,0,2675664,653028,3489156,0,0,1,19,22,7,5,1,94,0,0

脚本:

cat vmstat.out | awk 'BEGIN{"date +'%Y,%m,%d,%H,%M,%S'"| getline dt;}{if (NR> 2) {i=1;while (i < NF) {rec=rec","$i; i++;} print dt,rec;}}'

我从脚本中获得的输出:

2016,05,19,23,53,58 ,1,0,0,2675664,653028,3489156,0,0,1,19,22,7,5,1,94,0

请注意预期输出中缺少的额外空格:58 ,1 和最后一个 0。我知道我的脚本中出现问题的部分是:rec=rec","$i

如何解决这个问题?

最佳答案

无需重新发明 awk 功能

$ awk -v OFS=, 'BEGIN{time=strftime("%Y,%m,%d,%H,%M,%S")} 
NR>2{$1=$1; print time,$0}' file

2016,05,19,15,12,29,1,0,0,2675664,653028,3489156,0,0,1,19,22,7,5,1,94,0,0

关于linux - 在 AWK 中 `rec=rec","$i` 没有按预期工作,其中 $i 是记录中的每个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37331566/

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