awk - 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;}'
但它把这些线一个接一个地放在一起,而不是“压缩”它们。
解决方案
您能否尝试使用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.
}
}
'
推荐阅读
- command-line-interface - 使用 ckanext-restricted 的 Ckan 扩展错误
- r - R代码将几个二分变量(来自多项选择题)转换为单个选择一个变量
- loops - 我该如何自动化呢?
- javascript - 如何更改以下样式?
- c# - Unity C#中奇怪的数字转换/编码
- javascript - 从javascript中的下拉列表列表中删除下拉列表
- python - Django 模型中的外键似乎不会自动生成
- azure - 使用 Azure Resource Graph 的 Azure 中的公共 ips 列表以及订阅名称、资源类型
- r - 如何平滑 geom_link 中路径的颜色?
- mysql - mariaDB 插件“反馈”已禁用