Home > Back-end >  Bring multiple matches with regex in bash, using while
Bring multiple matches with regex in bash, using while

Time:05-28

So I'm trying to make a bash script which brings the actual weather some extra info. It should call an API with curl, then it gets the info in json, and then parse the information with some regex. The API brings the temp for each hour of the day, which is a lot.

#!/bin/bash

text="{                  
    "temp": 286.92,
    "feels_like": 286.05,
    "temp_min": 286.17,
    "temp_max": 286.92,
    "pressure": 1019,
    "sea_level": 1019,
    "grnd_level": 959,
    "humidity": 65,
    "temp_kf": 0.75
    "temp": 263.92,     #<--these 2 "temp" are just examples I put     
    "temp": 277.92,     #in here so I can work better
   },

regex='((temp)...([0-9] [.]?[0-9] ))'

while [[ $text =~ $regex ]]; do
     echo ${BASH_REMATCH}
done
                                     

I want to get each one of the "temp": and print it to the user. It didn't work with an if statement because it matches only a single time, so I found that this can be done using a while statement. But this one I wrote results in a infinite loop of results!

My desired result is:

temp: 286.92
temp: 263.92
temp: 277.92

But what I get is an infinite loop of:

temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
temp: 286.92
...

CodePudding user response:

Read each line of the text, and do the pattern matching.

   regex='((temp)...([0-9] [.]?[0-9] ))'
   
   IFS=$'\n'; for line in $text; do
   if [[ $line=~ $regex ]]; then
           echo ${BASH_REMATCH[0]}
   fi
done

Live Demo

CodePudding user response:

Try learning to use jq to deal with JSON in bash. It is powerful and is designed for this.

If your curl query returns a single JSON, the command will just do your job:

curl https://someurl | jq -r '"temp: \(.temp)"'

If it returns a list of JSON, use the following instead:

curl https://someurl | jq -r '"temp: \(.[].temp)"'

  • Related