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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort a text delimited file 1

Status
Not open for further replies.

ale77

Programmer
Jul 18, 2003
38
US
Hello

I have a file with data like this test.txt:
Code:
1	3423	John	Michael	33	NY
2	5345	Silvia	Goodman	12	FL
3	5783	Lewis	Nieto	41	TX
4	9435	Martha	Fuchs	36	NJ
5	4721	Mark	Brown	28	CA

I would like to know how to read from that file and display the data sorted by any column eg State
Code:
5	4721	Mark	Brown	28	CA
2	5345	Silvia	Goodman	12	FL
4	9435	Martha	Fuchs	36	NJ
1	3423	John	Michael	33	NY
3	5783	Lewis	Nieto	41	TX

Right now I just have this:
Code:
$file_inp = 'c:\daily\test.txt';

open(HANDLE_FILEINP, "<$file_inp") || die "Couldn't open FILEINP.\n";

$prev_line    = " ";

while($cur_line = <HANDLE_FILEINP>)
  {
    $prev_line = $cur_line;
    $prev_line_chomped = $prev_line;
    chomp($prev_line_chomped);

    @field_data = split(/\t/, $prev_line_chomped);  
    print "$prev_line"
  }
   
close(HANDLE_FILEINP);
print(" \n");

Thanks in advance.
 
This should give you a start - it's using an array of arrays. Note that this uses an ASCII sort - if you're comparing numeric fields of varying length, you may not get the results you expect.

You might want to look in the Sort::Fields module for another approach.

Code:
my @records;
while ($_ = <DATA>) {
    chomp;
    push @records, [split("\t", $_ )];
}

# Change the field numbers to the field you want to sort by.
# This is sorting by state.
@records = sort {${$a}[5] cmp ${$b}[5]} @records;

foreach (@records) {
    print join("\t", @{$_}), "\n";
}

__DATA__
1	3423	John	Michael	33	NY
2	5345	Silvia	Goodman	12	FL
3	5783	Lewis	Nieto	41	TX
4	9435	Martha	Fuchs	36	NJ
5	4721	Mark	Brown	28	CA
 
Thanks rharsh!!
It's working just as I wanted.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top