By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,691 Members | 1,997 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,691 IT Pros & Developers. It's quick & easy.

Extracting data from text file from different lines

P: 1
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
Feb 9 '09 #1
Share this Question
Share on Google+
4 Replies


KevinADC
Expert 2.5K+
P: 4,059
Can we see what you have tried so far?
Feb 9 '09 #2

gpraghuram
Expert 100+
P: 1,275
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
Feb 10 '09 #3

P: 89
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.  
Feb 10 '09 #4

KevinADC
Expert 2.5K+
P: 4,059
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. }
Feb 10 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.