我正在嘗試制作一個 bash scraper,我已經設法提取資料,但由于日期和溫度不在同一行上,所以很難使用 grep 獲取 f.ex 今天溫度的行。我希望將結果輸出到檔案中。
我試過 grep -E -o '[2022]-[11]-[15]' | grep“攝氏度” | grep -E -o '[0-9]{1,2}.[0-9]{1,2}' > file.txt API 結果
`product class="pointData">
<time datatype="forecast" from="2022-11-14T18:00:00Z" to="2022-11-14T18:00:00Z">
<location altitude="4" latitude="60.3913" longitude="5.3221">
<temperature id="TTT" unit="celsius" value="8.2"/>
<windDirection id="dd" deg="146.5" name="SE"/>
<windSpeed id="ff" mps="0.5" beaufort="1" name="Flau vind"/>
<windGust id="ff_gust" mps="1.2"/>
<humidity unit="percent" value="82.5"/>
<pressure id="pr" unit="hPa" value="1014.5"/>
<cloudiness id="NN" percent="45.1"/>
<fog id="FOG" percent="0.0"/>
<lowClouds id="LOW" percent="4.5"/>
<mediumClouds id="MEDIUM" percent="0.0"/>
<highClouds id="HIGH" percent="39.9"/>
<dewpointTemperature id="TD" unit="celsius" value="5.0"/>
</location>
</time>
<time datatype="forecast" from="2022-11-14T17:00:00Z" to="2022-11-14T18:00:00Z">
<location altitude="4" latitude="60.3913" longitude="5.3221">
<precipitation unit="mm" value="0.0" minvalue="0.0" maxvalue="0.0"/>
<symbol id="PartlyCloud" number="3" code="partlycloudy_night"/>
</location>
</time>
<time datatype="forecast" from="2022-11-14T19:00:00Z" to="2022-11-14T19:00:00Z">
<location altitude="4" latitude="60.3913" longitude="5.3221">
<temperature id="TTT" unit="celsius" value="8.7"/>
<windDirection id="dd" deg="112.5" name="SE"/>
<windSpeed id="ff" mps="0.4" beaufort="1" name="Flau vind"/>
<windGust id="ff_gust" mps="0.8"/>
<humidity unit="percent" value="75.6"/>
<pressure id="pr" unit="hPa" value="1013.8"/>
<cloudiness id="NN" percent="57.5"/>
<fog id="FOG" percent="0.0"/>
<lowClouds id="LOW" percent="1.1"/>
<mediumClouds id="MEDIUM" percent="0.4"/>
<highClouds id="HIGH" percent="55.4"/>
<dewpointTemperature id="TD" unit="celsius" value="4.4"/>
</location>
</time>
輸出到檔案應該是。
8.2
uj5u.com熱心網友回復:
grep -A3 '2022-11-14' -m1 inputfile.txt | \
grep -P -o "<temperature.*celsius.*\"\K\-?[0-9]{1,2}\.[0-9]{1,2}"
8.2
- -A3匹配后列印 3 行
- -m1在第一次匹配后停止
- -P使用 Perl 正則運算式
- -o僅搜索匹配項
- \K忽略之前的內容
- -?get - 用于負溫度
- [0-9]{1,2}.[0-9]{1,2}攝氏溫度
您還可以使用xq:
$ date="2022-11-14"
$ xq -r '.product.time[0] | select (."@from" | contains("'$date'")) // null | '\
'.location|.temperature|(if ."@unit" == "celsius" then ."@value" else "error" end)' \
< input.html
8.2
或者如@AndyLester 所說,使用 xpath。
$ date="2022-11-14"
$ xmllint --xpath '//time[starts-with(@from,"'$date'")][1]'\
'//temperature[@unit="celsius"]/@value' input.txt |\
grep -Po '[-]?\d \.\d '
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/535861.html
標籤:狂欢网页抓取xml解析
