1

Given the following string:

arn:aws:secretsmanager:us-east-1:3264873466873:secret:foo/bar 1564681234.974 foo/bar {"username":"admin","password":"admin123","secret_key":"KASJDFJHAKHFKAHASDF"} 4e397333-3797-4f0b-ad7e-8c1cc0ed041c VERSIONSTAGES AWSCURRENT

Within a shell script, how do you extract just the JSON portion to end up like this:

{"username":"admin","password":"admin123","secret_key":"KASJDFJHAKHFKAHASDF"}

I was able to do it using two sed commands:

echo $longString | sed 's/^.*{/{/' | sed 's/}.*$/}/'

but was wondering if there is a way to do it using only one command.

1
  • 2
    grep -o '{.*}' maybe? Commented Aug 1, 2019 at 20:58

5 Answers 5

3

To extract continuous part of the input, you can use grep with its -o option (if supported on your system). It tells grep to only output the matching part.

grep -o '{.*}'
Sign up to request clarification or add additional context in comments.

Comments

1

For extracting columns, use awk:

echo $longString | awk '{print $4}'

Or cut:

echo $longString | cut -f 4 -d ' ' 

Beware if you have spaces in your JSON data. You might be better off using jq to process the results of aws secretsmanager list-secrets and similar.

Comments

0

You can use

echo $longString | sed -n 's|.*\({.*}\).*|\1|p'

to match and print the desired pattern

Comments

0

you can just join the sed commands to a single command sed 's/^.*{/{/;s/}.*$/}/'

Comments

0

This awk should do. I will handle if there are any space in the string.

echo $string | awk -F"[{}]" '{print $2}'
"username":"admin","password":"admin123","secret_key":"KASJDFJHAKHFKAHASDF"

Comments

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.