Awk 将时间戳追加到命令输出

Awk 将时间戳追加到命令输出,awk,sed,Awk,Sed,我运行以下命令: 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-primar

我运行以下命令:

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命令,但我把输出搞砸了

i、 e:

所需的输出将是:

{"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"}

如何获得所需的输出?

您基本上已经得到了它,只是一些需要解读的引号和反斜杠

我还用调用awk中的
sub
来替换sed命令,以便将所有内容都保存在一个命令中(另外,由于时间戳中有一个
,您不想替换,因此在awk中实际上更简单)


“我尝试了不同的awk或sed命令”-编辑您的问题以添加一个或多个尝试!修复它可能是件小事。我用一个我尝试过的例子编辑了我的原始帖子。看看
ts
。。。我得到:{“timestamp”:“,”service”:“service primary”,“server”:“server”,“status”:“started”}您设置了timestamp变量吗?在你的问题中,你有
TIMESTAMP=$(date-Is)
。我没有注意到我把它注释掉了。非常感谢。这个命令非常有效。
{"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"}
$ ... | 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"}