Search code examples
pythonbashsortinglslistdir

modify bash ls command to sort by ending characters


I have a directory with a lot of log files like sample_step1[_step2[_step3]].log

to check complition of each step I run python ls_end.py, which is

from os import listdir
from os.path import getsize, isfile

def end_sort(s): return s[::-1]


files = [i for i in listdir('.') if isfile(i) and not i.startswith('.')]
for i in sorted(files, key=end_sort):
    print("{:10.2f}\t{}".format(getsize(i)/1024, i))

is there any alternative in bash to sort files in directory from the ending ?


Solution

  • That seems like a highly unorthodox sorting method, but you could do it easily enough in bash if you have the util-linux package installed, which includes the rev utility:

    ls | rev | sort | rev 
    

    Another possibility, which is a slightly more conventional sort, would be:

    ls | sort -t_ -k4 -k3,3 -k2,2
    

    That will sort each step field in normal order, but will place files with missing step2 and step3 in a different order, which may or may not be what you're looking for.