ls to list files sorted by filename without the extension
Sebastian Wright
I want to list a bunch of files that are sorted by their names excluding the file extension. I have these files in a directory
$ls
mobility_arXiv.tex
mobility_SR.bbl
paper-hj-mm.tex
paper-hj-mm-vp-rkp.tex
paper-hj.texI want the output to be
mobility_arXiv.tex
mobility_SR.bbl
paper-hj.tex
paper-hj-mm.tex
paper-hj-mm-vp-rkp.texIs there a way to achieve this.
52 Answers
You can pipe the output of ls into cut, which cuts fields, specifying "." as the delimiter. The result can then be sorted by piping into sort.
ls | cut -f 1 -d '.' | sortIf you need to handle dots "." in the filename you can use
ls | rev | cut -d . -f 2- | rev | sortThis works by first reversing each listing returned by ls, then cutting away the first (originally last) field, then reversing again.
NOTE: Cannot be used with colour output
If you wanted to keep the extension anyway, and just sort by the first part of the filename you can use
ls | sort -k 1,1 -t . Here you're telling sort to use "." as the delimiter and sort according to key(field) 1.
5The ls command sorts files by filename alphabetically ascending by default. The extension is part of the filename so the best you can do, if you don't need the extension in the output is:
ls | cut -f 1 -d '.' | sortUPDATE
A better solution:
ls | sort -k 1,1 -t .Here sort is told to use just field number 1 and the dot as field separator. So it's ignoring the extension but not cutting it out.
2