0

How can I convert the shell command output to an array so I can print variables as uniqueMetrics[0], uniqueMetrics[1] etc?

const uniqueMetrics = await execShellCommand('aws cloudwatch list-metrics --namespace AWS/ApiGateway  | jq -r .Metrics[].Dimensions[].Name | sort -u')

console.log(uniqueMetrics);

output:

ApiId
ApiName
Stage

It seems the data is returned as follows with \r and \n.

[ 'ApiId\r\nApiName\r\nStage\r\n' ]

So I'm guessing I'd need to search and replace these strings first. Am I thinking right?

1 Answer 1

1

You should be able to use String.split() function:

let uniqueMetricsArray = uniqueMetrics.split('\r\n');

For better compatibility, it might make sense to make it work for both \r\n and just \n using RegExp:

let uniqueMetricsArray = uniqueMetrics.split(/\r?\n/);
Sign up to request clarification or add additional context in comments.

2 Comments

It returns an empty array value as well. Any idea how to fix that as well? [ 'ApiId', 'ApiName', 'Stage', '' ]
@John filter the result or trim the input string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.