LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   using grep to find text sections (https://www.linuxquestions.org/questions/linux-newbie-8/using-grep-to-find-text-sections-4175511315/)

lapishater276 07-16-2014 03:48 PM

using grep to find text sections
 
i want to use the grep tool to be able to find a city in an xml document by locating the tag after the state and the for before the town. here is part of the code. this code is located in ~/.cache/weather.xml
<description>Yahoo! Weather for Town, State</description>

how would i be able to find the code?

szboardstretcher 07-16-2014 03:50 PM

Should be simple. Can you provide a bit more of the XML that is related to what you requested?

smallpond 07-16-2014 05:02 PM

Perl would be better:

Code:

perl -ne '/Weather for (.*)\</ && print $1,"\n";' < file

kooru 07-17-2014 12:46 AM

You can use sed. (just a fast example, the syntax can be improved)

if you want to extract just "Town"
Code:

echo "<description>Yahoo! Weather for Town, State</description>" | sed -n 's/.*for \(.*\),.*/\1/p'
if you want to extract "Town, State"
Code:

echo "<description>Yahoo! Weather for Town, State</description>" | sed -n 's/.*for \(.*\)<.*/\1/p'

lapishater276 07-17-2014 06:44 AM

how would i use sed (or perl) to look into the xml document?

lines 1-22 of xml document
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>

<title>Yahoo! Weather - Town, State</title>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Town__State/*http://weather.yahoo.com/forecast/USAII000_A.html</link>
<description>Yahoo! Weather for Town, State</description>
<language>en-us</language>
<lastBuildDate>Thu, 17 Jul 2014 6:14 am CDT</lastBuildDate>
<ttl>60</ttl>
<yweather:location city="Town" region="State" country="United States"/>
<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
<yweather:wind chill="52" direction="0" speed="0" />
<yweather:atmosphere humidity="94" visibility="10" pressure="30.08" rising="0" />
<yweather:astronomy sunrise="5:53 am" sunset="8:44 pm"/>
<image>
<title>Yahoo! Weather</title>
<width>142</width>
<height>18</height>
<link>http://weather.yahoo.com</link>
<url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url>
</image>

keefaz 07-17-2014 07:17 AM

Code:

perl -ne '/for (.*),.*<\/description>/ and print "$1\n"' ~/.cache/weather.xml
- matches "the tag after the state", so "</description>"
- print chars after the "for " and before the ","


All times are GMT -5. The time now is 06:39 AM.