Dean Do wrote: > > Hello, Hello,
> I'm rather new to PERL. How do I go about sorting > a simple text file using PERL? This is what I want > to accomplish. > > # sort /etc/passwd > /etc/passwd-new > # mv /etc/passwd-new /etc/passwd Are you sure you want to modify /etc/passwd? Which field do you want to sort on? #!/usr/bin/perl # *** UNTESTED *** use warnings; use strict; use Fcntl qw( :flock :seek ); my $file = '/etc/passwd'; open my $fh, '+<', $file or die "Cannot open $file: $!"; flock $fh, LOCK_EX or die "Cannot lock $file: $!"; # sort on the user name field my @records = map $_->[ 1 ], sort { $a->[ 0 ] cmp $b->[ 0 ] } map [ (split /:/)[ 0 ], $_ ], <$fh>; # sort on the UID field #my @records = map $_->[ 1 ], # sort { $a->[ 0 ] <=> $b->[ 0 ] } # map [ (split /:/)[ 2 ], $_ ], # <$fh>; seek $fh, 0, SEEK_SET or die "Cannot seek on $file: $!"; # you could also use truncate() here but since you are not # changing the size of the data it is not necessary. print $fh @records or die "Cannot print to $file: $!"; # close and unlock the file close $fh; __END__ If you are going to try this out, MAKE A BACKUP COPY of the file first! If you screw up the /etc/passwd file without a backup you are going to be in a world of hurt. John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]