首页 > 解决方案 > awk zip 行,如 python zip

问题描述

嗨,我希望压缩 2 行,最好使用 awk。

假设我们有这个输出

$ free -m
              total        used        free      shared  buff/cache   available
Mem:           7875          53        7523           8         298        7579
Swap:            99           0          99

我希望这样显示它。

total: 7875, used: 53, free: 7523, shared: 8, buff/cache: 298, available: 7579

我已经根据另一个问题尝试过这个。

free -m | awk '$1=="Mem:" || $1=="total" {key=$0; getline; print key ", " $0;}'

但它把这些线一个接一个地放在一起,而不是“压缩”它们。

标签: awk

解决方案


您能否尝试使用free命令进行跟踪、编写和测试。

free -m | 
awk '
  FNR==1{
    for(i=1;i<=NF;i++){ arr[i]=$i }
  }
  FNR==2{
    for(i=2;i<=NF;i++){
      printf("%s%s",arr[i-1]":" OFS $i,i==NF?ORS:",")
    }
  }
'

或尝试以下操作:

free -m | 
awk '
  FNR==1{
    split($0,arr)
  }
  FNR==2{
    for(i=2;i<=NF;i++){
      printf("%s%s",arr[i-1]":" OFS $i,i==NF?ORS:",")
    }
  }
'

说明:为上述添加详细说明。

free -m |                             ##Running free -m command and sending its output to awk command as an input here.
awk '                                 ##Starting awk program from here.
  FNR==1{                             ##If this is first line then do following.
    for(i=1;i<=NF;i++){ arr[i]=$i }   ##Traversing through all fields and created array arr with index of field number and value is current field value.
  }
  FNR==2{                             ##If this is 2nd line then do following.
    for(i=2;i<=NF;i++){               ##Traversing through all fields from 2nd field onwards.
      printf("%s%s",arr[i-1]":" OFS $i,i==NF?ORS:",") ##Printing array value along with current field value as per OP requirement here.
    }
  }
'

推荐阅读