Search code examples
linuxfindalphabetical

Sorting find command by filename


I am looking to sort the output of a find command alphabetically by only the filename, not the whole path.

Say I have a bunch of text files:

./d/meanwhile/in/b.txt
./meanwhile/c.txt
./z/path/with/more/a.txt
./d/mored/dddd/d.txt

I am looking for the output:

./z/path/with/more/a.txt
./d/meanwhile/in/b.txt
./meanwhile/c.txt
./d/mored/dddd/d.txt

I have tried:

find . -type f -name '*.txt' -print0 | sort -t
find . -name '*.txt' -exec ls -ltu {} \; | sort -n
find . -name '*.txt' | sort -n

...among other permutations.


Solution

  • The straightforward way would be to print each file (record) in two columns -- filename and path -- separated by some character sure to never appear in the filename (-printf '%f\t%p\n'), then sort the output on first column only (sort -k1), and then strip the first column (cut -d$'\t' -f2):

    find . -type f -name '*.txt' -printf '%f\t%p\n' | sort -k1 | cut -d$'\t' -f2
    

    Just note that here we use the \t (tab) and \n (newline) for field and record separators, assuming those will not appear as a part of any filename.