Skip to content
Advertisement

Sort on specific part of filename in shell script

I have a list of files which I want to delete except 2 of the most recent ones. The files are named as “filename_dd_mm” for example “filename_19_05”. If I do

find . -name "filename_??_??*"|sort

It sorts them according to the day. What I want is to sort them by month first and then the day. Can someone please guide me to do this.

P.S. I learnt shell scripting only a few days ago, so I don’t have much knowledge and couldn’t any examples relating to this.

Advertisement

Answer

Try this:

find . -name 'filename_??_??*'  | sort   -t _ -k3n -k2n
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement