2

I want to delete oldest files in a directory when the number of files is greater than 5. I'm using

(ls -1t | tail -n 3)

to get the oldest 3 files in the directory. This works exactly as I want. Now I want to delete them in a single command with rm. As I'm running these commands on a Linux server, cd into the directory and deleting is not working so I need to use either find or ls with rm and delete the oldest 3 files. Please help out. Thanks :)

user2340345
  • 793
  • 4
  • 16
  • 38
  • _cd into the directory and deleting is not working_ - how's that? `ls -1t` also only operates on the current directory, so since that works, it must already be in the right directory. – Armali Mar 29 '16 at 12:58

3 Answers3

2

If you want to delete files from some arbitrary directory, then pass the directory name into the ls command. The default is to use the current directory.

Then use $() parameter expansion to transfer the result of tail into rm like this

rm $(ls -1t dirname| tail -n 3)
Neil Masson
  • 2,609
  • 1
  • 15
  • 23
0
rm $(ls -1t | tail -n 3) 2> /dev/null
mitghi
  • 889
  • 7
  • 20
0

ls may return No such file or directory error message, which may cause rm to run unnessesary with that value.

With the help of following answer: find - suppress "No such file or directory" errors and https://unix.stackexchange.com/a/140647/198423

find $dirname -type d -exec ls -1t {} + | tail -n 3 | xargs rm -rf
alper
  • 2,919
  • 9
  • 53
  • 102