0

So I have a multi-line string that I need to pull multiple items from (1 regex string capturing multiple groups). I need to loop through these results.

Example of what I have so far:

#!/bin/bash
string='
    {
        "id" : 45,
        "name" : "John Doe",
        "address" : "123 Fake Street"
    },
    {
        "id" : 46,
        "name" : "Jane Doe",
        "address" : "234 Somewhere Road"
    }
'
regex='\{[^\}]*id" : ([0-9]*)[^\}]*name" : "([a-zA-Z ]*)"[^\}]*address" : "([a-zA-Z0-9 ]*)"[^\}]*}'
if [[ "$string" =~ $regex ]]; then
echo "${BASH_REMATCH[1]} | ${BASH_REMATCH[2]} | ${BASH_REMATCH[3]}"
fi

This outputs:

45 | John Doe | 123 Fake Street

How can I loop thru all the results, to output:

45 | John Doe | 123 Fake Street
46 | Jane Doe | 234 Somewhere Road
47 | Someone else | 777 Nowhere Dr
... etc

Thank you for your help!

Cyrus
  • 84,225
  • 14
  • 89
  • 153
chrisr747
  • 13
  • 4
  • Parse JSON with `jq`, it will be much cleaner. If you do not want to use `jq`, you may still use other tools that are very likely to be already available, like Python. See [Parsing JSON with Unix tools](https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools). – Wiktor Stribiżew Apr 07 '18 at 19:55
  • If `jq` is not available. With GNU awk: `echo "$string" | awk -F '( : "*|"|,)' '/"(id|name)"/{printf($4 " | ")} /"address"/{print $4}'` – Cyrus Apr 07 '18 at 20:24
  • See here http://rextester.com/RQGN23785 – A l w a y s S u n n y Apr 08 '18 at 02:27
  • `echo "[ $string ]" | jq -r '.[] | "\(.id) | \(.name) | \(.address)"'` – Cyrus Apr 08 '18 at 07:42

0 Answers0