0

I'm learning a shell scripting and I'm having problems to structure my script. I need to create a script that exclude files of a specific format (example *.txt), keeping only the 5 most recent files, other format files and folder.

Until now, I've wrote this code below (it doesn't work...):

#!/bin/bash

cd testfolder ; rm $(find -name '*.txt' -exec ls -t | awk 'NR>5')

Thanks in advance for the help!

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • `find -name '*.txt' -exec ls -t {} \;` may be a better option, but why is `NR>5` the condition? It will not make it keep the 5 most recent files – Ted Lyngmo Jan 23 '23 at 17:05
  • Note that `find` -- unlike `ls` -- does not do any sorting by default. – Charles Duffy Jan 23 '23 at 17:12
  • You might want to start with [BashFAQ #3](https://mywiki.wooledge.org/BashFAQ/003). – Charles Duffy Jan 23 '23 at 17:13
  • I saw the awk command on internet and tried it, but I admit that I don't know how it works. If I use this find command, can I keep the 5 most recent files? – Gustavo Silva Jan 23 '23 at 17:13
  • The find command Ted gave you works only for _small_ numbers of files (after being changed to use `+` instead of `\;`). Give it too many to fit on a single command line and it'll break, by splitting the files into batches and sorting only the individual batches. It also has the problems described in [ParsingLs](https://mywiki.wooledge.org/ParsingLs). I do not recommend its use; see the answers on the linked duplicate instead, or the FAQ link above. – Charles Duffy Jan 23 '23 at 17:14
  • Use `+` instead of `;` so that all the filenames will be put into a single call to `ls` (unless there are so many that it exceeds the maximum line length). – Barmar Jan 23 '23 at 17:15

0 Answers0