Search code examples
linuxbashshellls

Removing files in a sub directory based on modification date


Hi so I'm trying to remove old backup files from a sub directory if the number of files exceeds the maximum and I found this command to do that

ls -t | sed -e '1,10d' | xargs -d '\n' rm

And my changes are as follows

ls -t subdirectory | sed -e '1,$f' | xargs -d '\n' rm

Obviously when I try running the script it gives me an error saying unknown commands: f

My only concern right now is that I'm passing in the max number of files allowed as an argument so I'm storing that in f but now I'm not too sure how to use that variable in the command above instead of having to set condition to a specific number.

Can anyone give me any pointers? And is there anything else I'm doing wrong?

Thanks!


Solution

  • The title of your question says "based on modification date". So why not simply using find with mtime option?

    find subdirectory -mtime +5d -exec rm -v {} \;
    

    Will delete all files older than 5 days.