Connecting Tech Pros Worldwide Help | Site Map

Extracting data from text file from different lines

Newbie
 
Join Date: Feb 2009
Posts: 1
#1: Feb 9 '09
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's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#2: Feb 9 '09

re: Extracting data from text file from different lines


Can we see what you have tried so far?
gpraghuram's Avatar
Expert
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,256
#3: Feb 10 '09

re: Extracting data from text file from different lines


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
Member
 
Join Date: Jul 2008
Posts: 70
#4: Feb 10 '09

re: Extracting data from text file from different lines


Let me know whether this is helpful

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  2. $counter =0;
  3. while(<>) {
  4.         chomp $_;
  5.         my(@v) = split(/\t/,$_);
  6.         $diff = $counter%2;
  7.         if($diff == 0)  {
  8.         push(@final, $v[7]);
  9.         $counter++;
  10.         }
  11.         else {
  12.         push(@final, $v[8]);
  13.         $counter++;
  14.         }
  15.  
  16. }
  17.  
  18. Regards
  19.  
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#5: Feb 10 '09

re: Extracting data from text file from different lines


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

Expand|Select|Wrap|Line Numbers
  1. open (FILE ,"somefile");
  2. while ($line = <FILE>) {
  3.    $nextline = <FILE>;
  4.    if ($line && $nextline)  {
  5.       do something with $line (lines 1,3,5,7,etc)
  6.       do something with $nextline (lines 2,4,6,8, etc)
  7.    }
  8. }
Reply

Tags
column, extract, file, lines, text