in reply to Regex to select multiple lines
Ok, some heavy assumptions in the following code, but oh well. Here goes:
#! /usr/bin/perl use strict; # Assume a blank line to mean no whitespace $/ = "\n\n"; foreach my $record ( <DATA> ) { chomp( $record ); my @data = split( "\n", $record ); # Take the last element of the last three lines in the record my $txname = ( split( / /, $data[ -3 ] ) )[-1]; my $txtime = ( split( / /, $data[ -2 ] ) )[-1]; my $errorcode = ( split( / /, $data[ -1 ] ) )[-1]; print "$txname\t\t\t$txtime\t\t$errorcode\n"; } __DATA__ Message Type: Name: Someone Time: Now Errorcode: 42 Message Type: Seismic instability Source: Japan Name: Anyone Time: Yesterday Errorcode: 23 Message Type: Author: Lewis Carrol Work: The hunting of whatever Name: Bellman Time: 12:32:1892 Errorcode: Snark!
The main point here is the use of the Input Record Separator ($/) to split the file into records. Then you can split on newlines and fetch the last three rows. The code above contains quite a bit of room for improvement in the regex-department (grabbing results into $1 and friends, for example), but I'll not muddy my point about the $/.
On my box, this (untidily) prints:
Someone Now 42 Anyone Yesterday 23 Bellman 12:32:1892 Snark!
Good luck!
pernod
--
Mischief. Mayhem. Soap.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex to select multiple lines
by beeny (Initiate) on Dec 09, 2004 at 17:02 UTC |