Reputation: 349
I run the following command:
sudo clustat | awk '/primary/ {print "{\"" $1 "\",\"server\":\"" $2 "\",\"status\":\""$3"\"}"}' |sed 's/\b:\b/":"/' >> test.log
Which gives me the following results:
{"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"}
How do I append a timestamp to the beginning of each string? I tried different awk or sed command but I screw up my output.
i.e :
#!/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
The desired output would be:
{"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"}
How can I get the desired output?
Upvotes: 1
Views: 356
Reputation: 10865
You basically had it, just some quotes and backslashes that needed to be unscrambled.
I also replaced the sed command with a call to sub
in the awk to keep everything in one command (also, since there's a :
within the timestamp that you don't want to replace, it's actually simpler to do in the 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"}
Upvotes: 1