Hi,
I am an old hat who is still living in the grep, sed, awk era. I am
trying to come up to speed with Perl since I am told that my toolkit
is completely outdated. I would appreciate if someone could help me
with a Perl equivalent of the following extremely simple awk command:
awk '/pattern/ {print $1 "-" $2 "-" $3 "\t" $NF}' inputfile
Thanks,
Larry
Awk says the pattern can be a conditional on the field data,
so it probably splits it up first. Although there is a $0 record
variable, so it depends on what when and where you wan't to
match.
Here is some very simple examples. Complex splitting can be done
using regular expressions for delemeter determination as well.
You can also forego split and parse the record fields with
a custom regular expression. I always thought DB's were
a better processor for records though.
Welcome to Perl.
sln
------------------------
use strict;
use warnings;
my @fld = ();
my ($pattern, $record) = ('w', '');
while ($record = <DATA>)
{
if ($record =~ /$pattern/)
{
# split fields up on white spaces (like awk)
@fld = split (' ', $record);
# do error checking, expected number of fields,
# more matching of field data, etc..
# ..
# print out some stuff
print "#1 - $fld[0]-$fld[1]-$fld[2]\t$fld[$#fld]\n";
}
# or
if ((@fld = split (' ', $record)) > 3 && $fld[3] eq $pattern)
{
print "#2 - $fld[0]-$fld[1]-$fld[2]\t$fld[$#fld]\n";
}
# or
if ((@fld = split (' ', $record)) > 3 && $fld[3] =~ /$pattern/)
{
print "#3 - $fld[0]-$fld[1]-$fld[2]\t$fld[$#fld]\n";
}
# or
if ((@fld = split (' ', $record)) > 3 && $fld[2] == 2007 && $fld[3] =~ /$pattern/)
{
print "#4 - $fld[0]-$fld[1]-$fld[2]\t$fld[$#fld]\n";
}
# or
if ((@fld = split (' ', $record)) > 4)
{
print "#5 - there are ".@fld." fields in this record\n";
}
}
__DATA__
Jan 20 2007 w
Jan 21 2007 w
Jan 22 2007 l
Jan 23 2008 w
Jan 24 2008 l
Jan 25 2008 l
Jan 26 2008 w extra
Jan 27 2008 l extra
Jan 28 2008 w extra