Extract a column of data using perl

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vkrishn
    New Member
    • Sep 2006
    • 1

    Extract a column of data using perl

    Hello i am extememly new to PERL and have a very basic question.

    Say i have two columns in a text file something like this...

    5330 1
    5380 5
    5390 6
    5400 9
    5410 11
    5420 15
    5430 23
    5440 38
    5450 57
    5460 86
    5470 111
    5480 171
    5490 226
    5500 347

    how do i extract just the first column and write to another file? is there an easy way to do that? i hae about 100 text files and need to extract the first column of each text file and write it to one big file (appending each time).. Any help is appreciated!!!!
  • pukur123
    New Member
    • Sep 2006
    • 61

    #2
    In two ways you can solve this problem.

    Fisrt one is.......

    1. Open each file
    2. Read line by line and use the split function to separate the words and then write the necessary word into the final file.

    @arr_file=("fil e1","file2","fi le3");

    open(FINAL, ">result.tx t");

    foreach $file in @arr_file
    {
    open(FILE, $file);

    while(defined($ line=<FILE>))
    {
    @arr_words=spli t(/\s+/,$line);

    print FINAL $arr[0];
    }

    close FILE;
    }

    close FINAL;

    Second one is.......

    Use the cut command of linux on each file and then redirect the output to the final file.


    @arr_file=("fil e1","file2","fi le3");

    system("touch result.txt");

    foreach $file in @arr_file
    {
    system(" cut -d' ' -f1 $file >> result.txt");
    }

    Comment

    Working...