1

I am not that good at bash scripting. I have a requirement to extract a substring between two words of a string. I tried different ways. Could some one help me pls?

This is my text "RegionName": "eu-west-1", "LatestAmiId": "ami-0ebfeadd9ccacfbb2",

Remember the the quotes and comma are the part of String. I need to extract the AMI ID alone, Means text between "LatestAmiId": " and ",

Any help pls?

3
  • 2
    What have you tried so far? Commented Jul 11, 2018 at 22:39
  • 2
    This looks like a section of JSON, have you considered using a tool like jq to work with JSON objects in scripts? It could prove to be much easier than specifically grabbing a substring Commented Jul 11, 2018 at 22:43
  • 1
    awk -F'"' '{print $8}' input_file Commented Jul 11, 2018 at 22:59

1 Answer 1

2

Assuming you have this string stored in a variable name input_text you can get the AmiId using sed like this

ami_id=$(echo "$input_text" | sed -e 's/.*LatestAmiId": "//' -e 's/",$//')

this uses two different sed scripts:

  • s/.*LatestAmiId": "// replaces all text up to and including LatestAmiId": " with nothing

  • s/",$// replaces the ", at the end of the line with nothing


As I mentioned in comments, jq is a tool that I have found really helpful when working with JSON objects in bash scripts. Since your input string looks like a section out of a json response from an AWS api, I highly recommend using a json tool rather than a regex to extract this information.

Sign up to request clarification or add additional context in comments.

6 Comments

Okay. Thanks Will .
I will try jq. Meanwhile the regex not replacing the first part of string . After the replacement I get "RegionName": "eu-west-1 ami-0ebfeadd9ccacfbb2 . I just needed the ami id
hmmm, it worked for me as expected, replaced the entire thing. Is it possible that there are newline characters in your string?
PCRE . matches everything except newlines by default
No there is no new line char. It not replacing "RegionName": "eu-west-1 .
|

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.