# keep n recent item in folder

Sometimes you create a script that generate something but you wanted to only keep N last item. There is couple way to achive this. This version works both on OSX and Linux.

```
$ (ls -t|head -n 5;ls)|sort|uniq -u|xargs rm
```

Basically it the `(..)` will capture together the output

1. `ls -t | head -n 5` will list files sort by time and get first 5 items
2. The second `ls` will list all file. Now it contains duplicate items for items we want to keep
3. `sort|uniq -u` will sort it, and remove those duplicate file in step 1. At this point it will contains only files that we want to delete (everything except files from step 1)
4. `xargs rm` will change the resulst into space separated value which is argument for `rm`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://til.yulrizka.com/unix/keep-n-recent-item-in-folder.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
