0

I would like to find specific files and remove them, but I need to leave the last 3 newest files. For example I have a structure like this and I have 5 .sql files.

├── db1
│   └── db.sql
├── db2
│   ├── db2.sql
│   └── db3.sql
├── db5.sql
├── emptydir1
├── emptydir2
├── emptydir4
├── emptydir5
├── emptyri3
├── filenam2
├── filenam3
├── filename
├── filename4
├── filename5
├── find_db.sh
└── noemptydir1
    └── database.sql

I would like to remove all .sql files and leave only the newest 3 (i.e db.sql, db2.sql, db3.sql) based on modification date. I can find all this files with:

find . -name "*.sql" -type f -ls | sort

which returns all needed file. I can't use -delete file as it will delete all files and I need to keep the newest 3. I can use i.e rm ls -t | awk 'NR>3' but it won't delete my specific files. Is there any way to achieve this?

EDIT

The best option that worked for me in this case was to use:

rm `find . -name "*.sql" |  xargs ls -lt | awk '{print $NF}' | tail -n +4`
Frendom
  • 508
  • 6
  • 24
  • "it won't delete my specific files" - what happens instead? – Nico Haase Oct 18 '22 at 13:26
  • @NicoHaase because it will delete files only in current directory and I need to remove files from directories deeper than I am – Frendom Oct 18 '22 at 13:29
  • Please add all clarification to your question by editing it. "leave the last 3 newest files" - that means, the last three per directory? – Nico Haase Oct 18 '22 at 13:37
  • @NicoHaase updated, hope it's much cleaner now – Frendom Oct 18 '22 at 13:45
  • If you can find the file with the 4th oldest mtime, just use it with `find . ! -newer "${fourth_oldest}" -delete`. You might want to add a `-type f` – William Pursell Oct 18 '22 at 15:31
  • @WilliamPursell not sure if this will work as intended. Let's say you have `directory1`. Inside this directory you have other directories which can have more directories etc and `.sql` files can be at different directories. Now, being in `directory1` I would like to delete all `.sql` files except 3 newest – Frendom Oct 18 '22 at 19:13
  • @Frendom Are you trying to keep 3 files in every subdirectory? If you just want to keep 3 files total, `-newer` seems like the easy approach. – William Pursell Oct 18 '22 at 19:19
  • @WilliamPursell yes, 3 files in total – Frendom Oct 19 '22 at 07:06

0 Answers0