Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

trying to read only the 2nd line in a file 3

Status
Not open for further replies.

jcarrott

Programmer
May 28, 2009
130
US
I need to read several files and create a new file with 3 values; the original file name, the company (field[6]) , and the PO number (field[10]).

I tried;
$vName1="out.txt";

@files= < $LAWDIR$sys/fax/POfax/* >;

foreach $file (@files)
{
open(IN, "$file") or die 'Could not open file1 for reading';
open(OUT, ">>$vPath2$vName1") or die 'Could not open file2 for writing';
foreach $line (<IN>)
{
chomp;
$field = split(/\,/, $line);
$vLn = $file . "," . $field[6] . "," . $field[10] . "\n";
print OUT $vLn;
}
}

This creates a output line for every line of the input file, and the values for field[6] and field[10] are always blank.

I only want to read the second line of each file.

Can somebody help me?
 
Why do you open the OUT file inside your foreach loop? You only need to open it once at the beginning.

I'd replace the second foreach loop with just:

Code:
    $line=<IN>; # discard first line
    $line=<IN>; # read second line
    chomp;
    [COLOR=red]@[/color]field = split(/\,/, $line);
    $vLn = $file . "," . $field[6] . "," . $field[10] . "\n";
    print OUT $vLn;

Also note the minor correction on the split line. You may want to add some error checking if there's a chance the input file would contain fewer than two lines.

Please post your code between [ignore]
Code:
 ...
[/ignore] tags in future.

Annihilannic.
 
Code:
open(OUT, ">>$vPath2$vName1") or die 'Could not open file2 for writing:$!';
for $file (@files)
{
    open(IN, "$file") or die 'Could not open file1 for reading';
    @file = <FILE>;
    close FILE;
    chomp @file;
    $field = split(/\,/, $file[1]);
    $vLn = $file . "," . $field[6] . "," . $field[10] . \n";
    print OUT $vLn;
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
You could also try something like this:
Code:
open OUT, "> outfile.txt";
foreach my $file (<file*.txt>) {
	open IN, "< $file";
	while (<IN>) {
		if ($. == 2) {
			print OUT join(',', $file, (split /,/)[6,10]);
			last;
		}
	}
	close IN;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top