954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

cut a column

I have executed a unix command whose output has a number of columns separated by whitespaces.How to extract a column from it and put it into an array using Perl.

laddu
Newbie Poster
9 posts since Nov 2006
Reputation Points: 10
Solved Threads: 0
 

Here's a quick script that will read the input from STDIN (<>) and chop everything by spaces, and construct a 2D matrix (2 dimensional array) out of it. Say, your input is something that looks like the output of the command <strong>ps aux</strong> , then you can use this script to "echo" the input:

#!/usr/bin/perl
# save this file as script.pl
use strict;
my @array;
my $counter = 0;
while (<>) {
    chomp($_);
    my @line = split(/\s+/, $_);
    $array[$counter] = \@line;
    $counter++;
}
# Print out the 2D array
foreach my $line (@array) {
     foreach my $item (@$line) {
         print "$item\t";
     }
     print "\n";
 }



And you can pipe the input to it like this:

$ ps aux | ./script.pl



-Josh www.qbangsolutions.com

josh dot kuo at qbangsolutions dot com

kuom
Newbie Poster
10 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You