转换shell命令" last"输出到json

时间:2018-04-09 15:20:39

标签: json shell jq

我可以将shell last输出转换为json

的任何选项

例如:最后一次输出

test   pts/0        1.1.1.1     Wed Jun 21 14:28 - 20:19  (05:51)

{
 name: "test",
 x1: "pts/0",
.
.
.
time: "(05:51)"
}

2 个答案:

答案 0 :(得分:2)

jq -R '
split("[[:space:]]+"; "g")
| select(length > 2) | select(.[0] != "")
| { "name":    (.[0]),
    "console": (.[1]),
    "ip":      (.[2]),
    "day":     (.[3])
  }
' < <(last)

答案 1 :(得分:0)

要考虑的另一个选择是使用正则表达式捕获变量。考虑例如:

capture("(?<name>^[^ ]+) +(?<token>[^ ]+) +(?<numeric>[0-9.]+) +(?<range>[^(]+)  +(?<time>.*)")

使用给定的输入,即:

test   pts/0        1.1.1.1     Wed Jun 21 14:28 - 20:19  (05:51)
输出将是:

{
  "name": "test",
  "token": "pts/0",
  "numeric": "1.1.1.1",
  "range": "Wed Jun 21 14:28 - 20:19",
  "time": "(05:51)"
}