Tuesday, February 1, 2022

[SOLVED] How to extract text between two patterns with sed/awk

Issue

I know this has been asked 1000 times here, but I read a lot of similar questions and still did not manage to find the right way to do this. I need to extract a number from a line that looks like this:

{"version":"4.9.123M","info":{"version":[2034.2],"description":""},"status":"OK"}

Expected output:

2034.2

This version number will not always be the same, but the rest of the line should.

I have tried working with sed but I am new to this and failed:

 sed -e 's/version":[\(.*\),"description/\1/'

output:

sed: -e expression #1, char 35: unterminated `s' command

I think the issue is that there are too many special characters involved in the line and I did not write the command very well.


Solution

If the version is always enclosed in [] and no other [ or ] is present in a line ,you can try this logic

STR='{"version":"4.9.123M","info":{"version":[2034.2],"description":""},"status":"OK"}'
echo $STR | awk -F'[' '{print $2}' | awk -F']' '{print $1}'


Answered By - Raghuram
Answer Checked By - Marie Seifert (WPSolving Admin)