bash:如何在 Linux 中从 .txt 文件创建键值对

bash:如何在 Linux 中从 .txt 文件创建键值对
w | awk 'NR==1 {print $1}' >file.txt
cat file
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
lava1    pts/0    157.48.149.102   05:03   31.00s  0.31s  0.31s -bash
azureuse pts/1    157.48.149.102   07:26    0.00s  0.07s  0.05s w

从上面的文本文件中,我想创建像 json 格式的键值对,如下所示 预期输出:

{
 "USER" : "lava1",
 "TTY" : "pts/1",
 "FROM" : "157.47.49.254",
 "LOGIN" : "12:32",
 "IDLE" : "5.00s"
}

答案1

我建议磨坊主对于这样的事情 - 具体来说,从“漂亮的打印”转换为 JSON:

$ mlr --ipprint --ojson cat file
{ "USER": "lava1", "TTY": "pts/0", "FROM": "157.48.149.102", "LOGIN@": "05:03", "IDLE": "31.00s", "JCPU": "0.31s", "PCPU": "0.31s", "WHAT": "-bash" }
{ "USER": "azureuse", "TTY": "pts/1", "FROM": "157.48.149.102", "LOGIN@": "07:26", "IDLE": "0.00s", "JCPU": "0.07s", "PCPU": "0.05s", "WHAT": "w" }

选择特定字段cut并重命名该LOGIN@字段:

$ mlr --ipprint --ojson cut -f USER,TTY,FROM,LOGIN@,IDLE then rename LOGIN@,LOGIN file
{ "USER": "lava1", "TTY": "pts/0", "FROM": "157.48.149.102", "LOGIN": "05:03", "IDLE": "31.00s" }
{ "USER": "azureuse", "TTY": "pts/1", "FROM": "157.48.149.102", "LOGIN": "07:26", "IDLE": "0.00s" }

答案2

因为你想生成 JSON,所以我们使用

w \
| tail -n +3 \
| jq -R '. | split("\\s+"; "g") | {USER:.[0], TTY:.[1], FROM:.[2], LOGIN:.[3], IDLE:.[4]}'

我正在使用tail它来跳过前两行w输出。

答案3

我看到了这个问题,并试图弄清楚。我接近成功了,但又遇到了一些阻碍。但最终,你的答案是这里

我所要求的只是为承担这项责任而获得一些荣誉。点赞!

相关内容