Sort files by basename
After a find, I'd like to sort the output by the basename (the number of directories is unknown). I know this can be done by splitting the basename from the dirname and sortin开发者_运维知识库g that, but I'm specifically looking for something where it's not necessary to modify the data before the sort. Something like sort --field-separator='/' -k '-1'
.
For this task, I'd turn to perl and the use of a custom sort function. Save the perl code below as basename_sort.pl, chmod it 0755, then you can execute a command such as you've requested, as:
find | grep "\.php" | ./basename_sort.pl
Of course, you'll want to move that utility somewhere if you're doing it very often. Better yet, I'd also recommend wrapping a function around it within your .bashrc file. (staying on topic, sh code for that not included)
#!/usr/bin/perl
use strict;
my @lines = <STDIN>;
@lines = sort basename_sort @lines;
foreach( @lines ) {
print $_;
}
sub basename_sort() {
my @data1 = split('/', $a);
my @data2 = split('/', $b);
my $name1 = $data1[@data1 - 1];
my $name2 = $data2[@data2 - 1];
return lc($name1) cmp lc($name2);
}
This can be written shorter.
find | perl -e 'print sort{($p=$a)=~s!.*/!!;($q=$b)=~s!.*/!!;$p cmp$q}<>'
Ended up with a solution of simply moving the base name to the start of the string, sorting, and moving it back. Not really what I was hoping for, but it works even with weirdzo file names.
精彩评论