Loading ...
Sorry, an error occurred while loading the content.

Re: sort a file by a field

Expand Messages
  • Damien Carbery
    Are you familar with split() and hashes? You could read in each line and place it all in a hash. Once you ve finished reading the file you can sort the hash by
    Message 1 of 2 , Mar 1, 2001
    • 0 Attachment
      Are you familar with split() and hashes?
      You could read in each line and place it all in a hash. Once you've
      finished reading the file you can sort the hash by social security
      number and print each line out.

      The script:
      #!/usr/local/bin/perl -w

      use strict;

      my ( %UnSorted, $SSN );
      if ( open( UNSORTED, "<list.txt" ) )
      {
      while( <UNSORTED> )
      {
      chomp;
      $SSN = ( split /,/ )[ 5 ]; # Get SSN.
      $UnSorted{ $SSN } = $_; # Store whole line.
      # Or replace the last two lines with:
      # $UnSorted{ ( split /,/ )[ 5 ] } = $_; # Store whole line.

      }
      close UNSORTED;

      open( SORTED, ">newlist.txt" );
      # The hash key is the SSN so sort by that.
      foreach ( sort keys %UnSorted )
      {
      print SORTED "$UnSorted{ $_ }\n"; # Print to file.
      }
      close SORTED;

      print "Sorted list in newlist.txt.\n";
      }
      else
      {
      print "Error opening file.";
      }


      --- In perl-beginner@y..., Denny Malloy <denny.malloy@n...> wrote:
      > Hi,
      >
      > Is there an easy way to sort a file by a field in that file using
      PERL?
      > I have an ASCII comma delimited file with name, address and social
      security
      > number. I need to sort this file by social security number only and
      write
      > it back out.
      >
      > Example of file:
      > name,address,city,state,zip,ssn
      >
      > THANKS for any input anyone might have!
      >
      > Denny Malloy
    Your message has been successfully submitted and would be delivered to recipients shortly.