我运行以下命令:
sudo clustat | awk '/primary/ {print "{\"" $1 "\",\"server\":\"" $2 "\",\"status\":\""$3"\"}"}' |sed 's/\b:\b/":"/' >> test.log
这给了我以下结果:
{"service":"serviceA-primary","server":"serverA","status":"started"}
{"service":"service1-primary","server":"server1","status":"started"}
{"service":"service2-primary","server":"server2","status":"started"}
{"service":"service3-primary","server":"server3","status":"started"}
{"service":"service4-primary","server":"server4","status":"started"}
如何在每个字符串的开头附加时间戳?我尝试了不同的awk或sed命令,但是搞砸了我的输出。
即:
#!/bin/bash
TIMESTAMP=$(date -Is)
sudo clustat | awk -v TS="${TIMESTAMP}" ' '/primary/ {print "{"{\"timestamp\": \""TS"\", \"" $1 "\",\"server\":\"" $2 "\",\"status\":\""$3"\"}"}' |sed 's/\b:\b/":"/' >> test.log
所需的输出是:
{"timestamp": "2016-10-11T18:44:39+0000", "service":"serviceA-primary","server":"serverA","status":"started"}
{"timestamp": "2016-10-11T18:44:39+0000", "service":"service1-primary","server":"server1","status":"started"}
{"timestamp": "2016-10-11T18:44:39+0000", "service":"service2-primary","server":"server2","status":"started"}
{"timestamp": "2016-10-11T18:44:39+0000", "service":"service3-primary","server":"server3","status":"started"}
{"timestamp": "2016-10-11T18:44:39+0000", "service":"service4-primary","server":"server4","status":"started"}
如何获得所需的输出?
答案 0 :(得分:1)
你基本上拥有它,只需要一些引号和反斜杠需要解读。
我还用awk中的sub
调用替换了sed命令,将所有内容保存在一个命令中(同样,因为在你不想替换的时间戳中有一个:
,它在awk中实际上更简单。)
$ ... | awk -v TS="${TIMESTAMP}" '/primary/ {sub(":","\":\"",$1); print "{\"timestamp\":\""TS"\", \"" $1 "\",\"server\":\"" $2 "\",\"status\":\""$3"\"}"}'
{"timestamp":"2016-10-11T18:44:39+0000", "service":"nfssvc-primary","server":"clusternode2.example.com","status":"starting"}