ASChakkalakal
ASChakkalakal

Reputation: 459

Extracting substring in bash script

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?

Upvotes: 1

Views: 83

Answers (1)

Will Barnwell
Will Barnwell

Reputation: 4089

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.

Upvotes: 2

Related Questions