Tuesday, October 25, 2022

[SOLVED] Extract phrases in bash (using sed)

Issue

I'm trying to extract some fragments of JSON document using regular expressions in bash. My goal is to catch every instance of this phrase and save them in new file. I thought that sed is good tool for such tasks.

I've tried sth like this:

sed '"temp":[0-9]+\.[0-9]*' weather.txt >> newFile.txt

Example of weather.txt:

{"temp":281.61,"temp_min":280.005,"temp_max":281.61,"pressure":1033.941,"sea_level":1033.941,"grnd_level":1024.038,"humidity":57,"temp_kf":1.6},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":2.19,"deg":6.817},"sys":{"pod":"n"},"dt_txt":"2019-04-19 18:00:00"},{"dt":1555707600,"main":{"temp":279.9,"temp_min":278.7,"temp_max":279.9,"pressure":1034.219,"sea_level":1034.219,"grnd_level":1024.211,"humidity":64,"temp_kf":1.2}

Expected result for input like this above is: :

 "temp":281.61 
 "temp":279.9

Despite trying defferent variations it isn't still correct. Do you have any idea how I can solve this problem?

Thank you in advance.


Solution

No, is for searching and replacing regular expressions in a file/files.
I would normally use for parsing JSON but your sample is an invalid JSON value and I assume so is your actual input, so, use instead:

$ grep -o '"temp":[0-9.]*' weather.txt > newfile.txt
$ cat newfile.txt
"temp":281.61
"temp":279.9


Answered By - oguz ismail
Answer Checked By - Terry (WPSolving Volunteer)