|
|
Returning only what matched a regular expression
|
|
|
|
Grizzled Veteran
Join Date: Jan 2002
Location: Melbourne, Australia
Status:
Offline
|
|
I have a file (actually a HTML file) with a number of links strewn through it. I would like to be able to use a tool to extract just the file name referenced by the links. I have looked at grep, awk and sed but they don't seem to do what I want. grep is fine but it returns the whole line where the match was found I only want the text matched by the regular expression. Anyone know how to do this, I would like to be able to do it on the command line instead of writing a script first (which is how I did it this time using perl).
Wesley
|
|
|
|
|
|
|
|
|
Senior User
Join Date: Jul 2000
Status:
Offline
|
|
To the best of my knowledge, you'd have to do it in Perl.
|
|
|
|
|
|
|
|
|
Mac Enthusiast
Join Date: Nov 2001
Location: Adelaide, South Australia
Status:
Offline
|
|
This isn't perfect (matching html with regular expressions is always a little dodgy!), but it might give you what you're after, or at least set you in the right direction:
perl -e 'undef $/;print join"\n",<>=~/HREF=\"(.*?)\"/sg' filename.html
Note that I'm guessing you want the target of the link: if not you'll have to modify the regex accordingly, but from what you've written that's probably not the problem.
[[Very quick explanation: links might cross lines, so the "undef $/" means that the whole file is sucked in as one blob. That blob is matched against the regex in list context, thus returning all the matches as an array. This array is printed out after being joined with spaces.]]
Best of luck,
Paul
|
|
|
|
|
|
|
|
|
Grizzled Veteran
Join Date: Jan 2002
Location: Melbourne, Australia
Status:
Offline
|
|
Ok cool, thanks for that. At least I'm reassured I wasn't missing anything and that perl is the way to go. My perl based solution was a script containing this:
foreach $line (<STDIN>) {
if($line =~ /">(Cimg[0-9]+\.jpg)<\/A/) {
print "http://www.host.com/2003-04-18/$1\n";
}
}
Obviously I changed the url, before you get any ideas they were pictures my friend took when we went out the other night.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Forum Rules
|
|
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
|
|
|
|
|
|