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

BusyBox环境下用sh/awk/sed将两行转为key=value格式字符串

实现方案

方法一:纯POSIX sh实现(无外部命令依赖)

利用POSIX标准的字符串裁剪语法直接操作变量,无需调用外部工具,兼容性最高:

#!/bin/sh

columns="usr sys nic idle io irq sirq"
points="2.2 4.5 0.0 93.1 0.0 0.0 0.0"
payload=""

while [ -n "$columns" ]; do
    # 提取当前首个字段
    cur_col="${columns%% *}"
    cur_point="${points%% *}"
    # 拼接结果,处理逗号分隔符
    if [ -z "$payload" ]; then
        payload="${cur_col}=${cur_point}"
    else
        payload="${payload}, ${cur_col}=${cur_point}"
    fi
    # 移除已处理的首个字段
    columns="${columns#* }"
    points="${points#* }"
    # 处理最后一个字段的边界情况,避免死循环
    if [ "$columns" = "$cur_col" ]; then
        break
    fi
done

执行后payload变量的值即为要求的格式。

方法二:使用BusyBox内置awk实现(代码更简洁)

BusyBox默认携带的awk完全支持以下语法,实现逻辑更清晰:

#!/bin/sh

columns="usr sys nic idle io irq sirq"
points="2.2 4.5 0.0 93.1 0.0 0.0 0.0"

payload=$(awk -v cols="$columns" -v pts="$points" 'BEGIN {
    split(cols, col_arr, " ")
    split(pts, point_arr, " ")
    res = ""
    for (i=1; i<=length(col_arr); i++) {
        if (i > 1) res = res ", "
        res = res col_arr[i] "=" point_arr[i]
    }
    print res
}')

两种方法均兼容BusyBox v1.30.1的默认环境,无需额外安装工具。

内容的提问来源于stack exchange,提问作者Andrey Valentsov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:57:03