Extracting data from text file from different lines

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nxstar
    New Member
    • Feb 2009
    • 1

    Extracting data from text file from different lines

    Hi

    I am confused about how to go about writing this program in perl.

    I have a text file with data in columns 8 and 9. I need to extract the data value from column 8 from the line being read and then extract the data value in column 9 from the next line. This needs to be repeated for all lines in the file. So, i would be taking data from column 8 from lines 1,3,5,7,ect and column 9 from lines 2,4,6,8..... I need to move these data values into an array.

    Thanks for all your help

    Nxstar
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Can we see what you have tried so far?

    Comment

    • gpraghuram
      Recognized Expert Top Contributor
      • Mar 2007
      • 1275

      #3
      You shuld first open the file.
      Then read the contents in a loop.
      After reading every line split the line using the split()
      Then take the required column and push it an array.
      close the file


      Raghu

      Comment

      • lilly07
        New Member
        • Jul 2008
        • 89

        #4
        Let me know whether this is helpful

        Code:
        #!/usr/bin/perl
        $counter =0;
        while(<>) {
                chomp $_;
                my(@v) = split(/\t/,$_);
                $diff = $counter%2;
                if($diff == 0)  {
                push(@final, $v[7]);
                $counter++;
                }
                else {
                push(@final, $v[8]);
                $counter++;
                }
              
        }
        
        Regards

        Comment

        • KevinADC
          Recognized Expert Specialist
          • Jan 2007
          • 4092

          #5
          All he has to do is read two lines of the file at a time:

          Code:
          open (FILE ,"somefile");
          while ($line = <FILE>) {
             $nextline = <FILE>;
             if ($line && $nextline)  {
                do something with $line (lines 1,3,5,7,etc)
                do something with $nextline (lines 2,4,6,8, etc)
             }
          }

          Comment

          Working...