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`