Sunday, July 10, 2022

[SOLVED] How to extract match in a proper way using grep or another command?

Issue

I have been looking into related questions on SO for days but I couldn't find an answer for my use-case. I want to grep a word after matching but without some special characters such as quotes, comma, dash. I have following line in my file.

...
"versionName": "1.1.5000-internal",
...

I want to extract the version itself without anything even -internal suffix, though but I am failed. Desired output would be as follows:

1.1.5000

What I've tried so far:

1. I tried below to extract version name without surrounding quotes but it failed.

grep -oP '(?<="versionName": )[^"]+(?=")' file.json

2. This one gives the match with all specials.

grep -oP '(?<="versionName": ).*' file.json | sed 's/^.*: //'

3. This one works the same as the second one.

grep '"versionName": ' file.json | sed 's/^.*: //'

I know there should be shorter and simpler approach but I am too bad at such stuff. Thanks in advance!


Solution

Using jq:

$ jq -r '.versionName|sub("-.*";"")' file.json 

Output:

1.1.5000


Answered By - James Brown
Answer Checked By - Marie Seifert (WPSolving Admin)