2011-02-01 110 views
1

我試圖從shell中的html頁面獲取文本,作爲腳本的一部分,向我顯示本地區的溫度。從html頁面獲取文本shell

然而,我不能讓我圍繞着如何使用grep頭正確

摘自網頁

</div><div id="yw-forecast" class="night" style="height:auto"><em>Current conditions as of 8:18 PM GMT</em><div id="yw-cond">Light Rain Shower</div><dl><dt>Feels Like:</dt><dd>6 &deg;C</dd><dt>Barometer:</dt><dd style="position:relative;">1,015.92 mb and steady</dd><dt>Humidity:</dt><dd>87 %</dd><dt>Visibility:</dt><dd>9.99 km</dd><dt>Dewpoint 

除了短砍下進一步

<dt>Feels Like:</dt><dd>6 &deg;C</dd> 

試圖抓住6 ° C

我試過了各種不同的戰術,包括grep和awk。 shell嚮導可以幫我嗎?

回答

1

嘗試

grep -o -e "<dd>.*deg;C</dd>" the_html.txt 

從手冊頁:

-e PATTERN, --regexp=PATTERN 
     Use PATTERN as the pattern. This can be used to specify 
     multiple search patterns, or to protect a pattern beginning with 
     a hyphen (-). (-e is specified by POSIX.) 

... 

-o, --only-matching 
     Print only the matched (non-empty) parts of a matching line, 
     with each such part on a separate output line. 

如果你想擺脫<dd></dd>過,只是追加| cut -b 5-12

+0

$ grep的-o -e 「

[^ <]*deg;C
」 /tmp/weather.html $〇一二三五二〇三一六三六6 ° C – 2011-02-01 21:20:51

+0

沒錯。更新了答案,包括如何擺脫這些dd標籤。 – aioobe 2011-02-01 21:22:34

0

如果x是你的輸入文件和HTML源作爲定期格式化爲你寫的,這應該工作 -

的grep度X | SED -e 「:S#^ >([0-9] {1,2} \ ° [CF])<#\ 1#」。

塞特

1

這給嘗試:

grep -Po '(?<=Feels Like:</dt><dd>).*?(?=</dd>)' | sed 's/ &deg;/°/' 

結果:

6°C