Reputation: 125
I have a directory with multiple text files. For example:
name1.txt
name2.txt
name3.txt
etc.. etc..
Each text file holds 1 line, on that line is a number i.e "10"
I was wondering if it'd be possible to somehow echo back the text file names of say the top 10 highest numbers of all the text files.
I was wondering if this could be done live via PHP or updated periodically via a bash script / cron Thanks!
Upvotes: 1
Views: 50
Reputation: 71
Not the most efficient idea but assuming you can't use a DB (otherwise you probably would):
<?php
$files = scandir('path/to/files/directory');
$rows = Array();
foreach($files as $file){
array_push($rows,file_get_contents('path/to/files/directory/'.$file);
}
arsort($rows);
$i = 0;
foreach($rows as $key => $row){
if($i <= 10){
echo 'On '.$files[$key].' the number is'.$row;
}
}
?>
Upvotes: 1
Reputation: 88766
grep . name*.txt | sort -nr -k2 | head -n 3
Output (e.g.):
name4.txt:1 name3.txt:123 name2.txt:444
Upvotes: 1
Reputation: 247022
With bash.
First, create some files:
for n in $(seq 20); do echo $RANDOM > name${n}.txt; done
Now, top 5:
$ for f in *; do printf "%s\t%d\n" "$f" $(<$f); done | sort -k2nr | head -n 5
name16.txt 30283
name12.txt 29976
name8.txt 28948
name4.txt 28256
name6.txt 28148
Just the filenames
$ for f in *; do printf "%s\t%d\n" "$f" $(<$f); done | sort -k2nr | head -n 5 | cut -f1
name16.txt
name12.txt
name8.txt
name4.txt
name6.txt
Upvotes: 0