bash shell script get substring from string containing quotes

I have a file named stuff.txt. There are multiple lines in that file. This is one of the lines in that file "somevalue": "4.2.1". I'm creating a shell script to get the value between the second set of double quotes (4.2.1). Here's what I have in my shell script so far:

substringVal=$(grep '\"somevalue\": \"' stuff.txt)

this snippet stores the value "somevalue": "4.2.1" in my variable substringVal but I want substringVal to contain 4.2.1 only. I don't know how long the substring will be so I can't just take a substring starting at a certain index for a certain amount of characters.

I've looked at awk but I haven't been able to get it to work for me. If anyone could point me in the right direction on how to modify my command in my shell script to get the substring from the line I'm grepping for I would appreciate it. Thanks in advance.

1

1 Answer

It worked this way for me:

substringVal=$(grep '\"somevalue\": \"' stuff.txt)
echo $substringVal
"somevalue": "4.2.1"
echo $substringVal | awk -F": " '{print $2}' | sed 's/\"//g'
4.2.1

So the awk command skips all until the ": ""-separator. And sed removes the last doble-quote.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like