Click to See Complete Forum and Search --> : sort file contents


just4spam
09-11-2003, 06:28 PM
I have a file that looks like this, here is the general format. PRIORITY, PATH, FILENAME, DESCRIPTION and USERNAME

priority path file description username
-----------------------------------------------------------

4 /home/my_home my_file1 d user1
2 /home/my_home my_file2 p user9
1 /home/my_home my_file3 p user7
3 /home/my_home my_file4 d user10

Now I have started writing this yet. I am looking for ideas. In the end I will write a program that will open this file every 60 seconds of so and orders the contnets based on the priority and write a new file that will look this this.

priority path file description username
-----------------------------------------------------------
1 /home/my_home my_file3 p user7
2 /home/my_home my_file2 p user9
3 /home/my_home my_file4 d user10
4 /home/my_home my_file1 d user1

Here is what I am thinking.

# open original file read one line at a time
# create a hash with the priority being the $key and the rest of the line being the $value.
# Comapre the $keys in the hash order then numberically
# write file with $key followed by $value.

I also thought about creating a array of arrays and compare there.

Any thoughts,

flar
09-11-2003, 10:47 PM
TMTOWTDI -- theres more than one way to do it..one way


open FILEHANDLE, file;
my @file = <FILEHANDLE>;
close FILEHANDLE;

my @sorted = sort(@file);

open FILEHANDLE, ">newfile";
foreach (@sorted) {
print FILEHANDLE "$_";
}
close FILEHANDLE;

dchidelf
09-11-2003, 11:35 PM
sort -n filename

or if you need to maintain the headers
...I will apologize in advance...This is completely obfuscated

cat filename | perl -ne 'print(/^[^\d]/?$_:sort { $a<=>$b }($_,<>))'

for each line
if the line read starts with something other than a number print it
otherwise print it and the rest of the file sorted numericly

just4spam
09-12-2003, 03:49 PM
Thanks guys,

THanks fior the input:

Here's what I came up with.
#
sub queJobs {
my %hash;
$file = "/queJobs";
$file2 = "/queJobsSorted";
open (QUEJOBS, $file) or die $!;
while (<QUEJOBS>) {
my $priority = (split /\s+/)[0];
$hash{$priority} = $_;
}
}
close QUEJOBS or warn $!;
open QUEJOBSORTED, ">$file2" or die $!;
print QUEJOBSORTED "$hash{$_}" for sort {$hash{$a} <=> $hash{$b}} keys %hash;
}
&queJobs;
#

Now if the lines of the file had no priority my solution prints it at the beginning of my new file. I would like it so it print lines with no priority at the bottom.

Thanks again.