On 10/28/07, Mahurshi Akilla <[EMAIL PROTECTED]> wrote:
> is there a way to get the "nth" column of a string in perl, similar to
> awk '{print $col_no}' in awk ?
snip
If I remember my awk correctly $col_no (e.g. $2) gives you the nth
space delimited field in the string (counting multiple spaces as a
single delimiter). The split function in Perl returns a list of items
delimited by the first argument and if that argument is a single space
it counts multiple spaces as one delimiter. You can extract the nth
element from this list using the indexing operators:
my $second_col = (split ' ', $string)[1];
Split's default arguments are ' ' and $_ so you can write this awk
awk '{print $2}' file
like this
perl -lne 'print((split)[1])' file
or this
perl -lpe '$_=(split)[1]' file
or even this
perl -pale '$_=$F[1]' file
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/