You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

合并awk命令实现多列存储单位转换计算

合并awk命令实现Segment Summary单位转换

需求说明

你需要处理Segment Summary的输出数据,完成这些单位转换:

  • 第4列:把字节数自动转换成KB/MB/GB(数值太小就保留字节单位)
  • 第7、8列:先把页面数乘4转成KB,再转换成合适的KB/MB/GB单位
    现在要把之前用的3个awk命令合并成一条,简化操作流程。

原始输入示例

Segment Summary:
1  2  3  1048576  5  6  262144  131072
2  3  4  20971520  6  7  5242880  2621440

现有冗余命令

之前分步处理用了3条awk命令:

# 转换第4列字节单位
awk '{if ($4 >= 1073741824) $4 = sprintf("%.2fGB", $4/1073741824); else if ($4 >= 1048576) $4 = sprintf("%.2fMB", $4/1048576); else if ($4 >= 1024) $4 = sprintf("%.2fKB", $4/1024); else $4 = $4"Bytes"}1' input.txt > temp1.txt
# 转换第7列(页面×4转KB后再转单位)
awk '{size = $7 *4; if (size >= 1073741824) $7 = sprintf("%.2fGB", size/1073741824); else if (size >= 1048576) $7 = sprintf("%.2fMB", size/1048576); else if (size >= 1024) $7 = sprintf("%.2fKB", size/1024); else $7 = size"KB"}1' temp1.txt > temp2.txt
# 转换第8列(页面×4转KB后再转单位)
awk '{size = $8 *4; if (size >= 1073741824) $8 = sprintf("%.2fGB", size/1073741824); else if (size >= 1048576) $8 = sprintf("%.2fMB", size/1048576); else if (size >= 1024) $8 = sprintf("%.2fKB", size/1024); else $8 = size"KB"}1' temp2.txt > output.txt

期望输出示例

Segment Summary:
1  2  3  1.00MB  5  6  1.00GB  512.00MB
2  3  4  20.00MB  6  7  20.00GB  10.00GB

合并后的单条awk命令

awk '
# 处理字节转合适单位的函数
function format_bytes(bytes) {
    if (bytes >= 1073741824)
        return sprintf("%.2fGB", bytes / 1073741824)
    else if (bytes >= 1048576)
        return sprintf("%.2fMB", bytes / 1048576)
    else if (bytes >= 1024)
        return sprintf("%.2fKB", bytes / 1024)
    else
        return bytes "Bytes"
}
# 处理页面数转合适单位的函数(先乘4转KB)
function format_pages(page) {
    size = page * 4
    if (size >= 1073741824)
        return sprintf("%.2fGB", size / 1073741824)
    else if (size >= 1048576)
        return sprintf("%.2fMB", size / 1048576)
    else if (size >= 1024)
        return sprintf("%.2fKB", size / 1024)
    else
        return size "KB"
}
# 第一行是标题,直接打印不处理
NR == 1 { print; next }
# 数据行处理:转换对应列后打印整行
{
    $4 = format_bytes($4)
    $7 = format_pages($7)
    $8 = format_pages($8)
    print
}
' input.txt > output.txt

命令解释

  • 把重复的单位转换逻辑抽成两个自定义函数,避免代码冗余
  • format_bytes专门处理第4列的字节单位转换
  • format_pages先将页面数乘4转成KB,再执行单位转换,对应第7、8列
  • 第一行标题直接跳过处理,避免破坏原有格式
  • 数据行依次处理目标列后,输出整行结果

内容的提问来源于stack exchange,提问作者Christopher Karsten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 06:12:40