k1308517 k1308517 - 5 months ago 14
Linux Question

Simple bash get part of a string

I have this text and more stored in a

$hello
:

"id":"1234"


How can I find id, and then get just the number?

There will be a lot of other text in the string.

Whole string is:
After making says:

{"self":"http://xxxxx:8081/rest/api/latest/version/1234","id":"1234","description":"desc","name":"vi1teast","archived":false,"released":false,"releaseDate":"2016-02-06","overdue":true,"userReleaseDate":"06/Feb/16","projectId":xxxxx}


I cannot use any JSON parsers, must be with string manipulation!

Answer

If you want to parse a JSON, use jq!

$ jq '.id' file
"1234"

And if you don't want to get the quotes, use -r:

$ jq -r '.id' file
1234

From the manual:

--raw-output / -r:

With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.

Note I had to tweak your JSON and write "projectId":"xxxxx" so that it is a valid one.

Comments