khinester
khinester

Reputation: 3520

use jq to format output and convert timestamp

I have the following code, which lists all the current aws lambda functions on my account:

aws lambda list-functions --region eu-west-1 | jq -r '.Functions | .[] | .FunctionName' | xargs -L1 -I {} aws logs describe-log-streams --log-group-name /aws/lambda/{} | jq 'select(.logStreams[-1] != null)' | jq -r '.logStreams | .[] | [.arn, .lastEventTimestamp] | @csv'

that returns

aws:logs:eu-west-1:****:log-group:/aws/lambda/admin-devices-block-master:log-stream:2018/01/23/[$LATEST]64965367852942f490305cb8707d81b4",1516717768514


i am only interested in admin-devices-block-master and i want to convert the timestamp 1516717768514 in as strflocaltime("%Y-%m-%d %I:%M%p")

so it should just return:

"admin-devices-block-master",1516717768514

i tried

aws lambda list-functions --region eu-west-1 | jq -r '.Functions | .[] | .FunctionName' | xargs -L1 -I {} aws logs describe-log-streams --log-group-name /aws/lambda/{} | jq 'select(.logStreams[-1] != null)' | jq -r '.logStreams | .[] | [.arn,[.lastEventTimestamp|./1000|strflocaltime("%Y-%m-%d %I:%M%p")]]' 
jq: error: strflocaltime/1 is not defined at <top-level>, line 1:
.logStreams | .[] | [.arn,[.lastEventTimestamp|./1000|strflocaltime("%Y-%m-%d %I:%M%p")]]                                                      
jq: 1 compile error
^CException ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

any advice is much appreciated

Upvotes: 1

Views: 2585

Answers (1)

EchoMike444
EchoMike444

Reputation: 1692

strflocaltime need jq version 1.6 , thanks to @oliv to remark it .

This is a very simple example that will replace a EPOCH with milliseconds by a local time .

date  -d @1572892409
Mon Nov  4 13:33:29 EST 2019

echo '{ "ts" : 1572892409356 , "id": 2 , "v": "foobar" } ' | \
          jq '.ts|=( ./1000|strflocaltime("%Y-%m-%d %I:%M%p")) '

{
  "ts": "2019-11-04 01:33PM",
  "id": 2,
  "v": "foobar"
}

A second version that test if ts exists

( 
  echo '{ "ts" : 1572892409356 , "id": 2 , "v": "foobar" } ' ; 
  echo '{ "id":3 }' ; 
  echo '{ "id": 4 , "v": "barfoo" }' 
) | jq 'if .ts != null 
        then  ( .ts|=( ./1000|strflocaltime("%Y-%m-%d %I:%M%p")) ) 
        else  . 
        end '

Upvotes: 1

Related Questions