# How to get a sorted list of the last n files?

**URL:** <https://forum.ansible.com/t/how-to-get-a-sorted-list-of-the-last-n-files/22953>\
**Category:** Ansible Project\
**Created:** [November 3, 2016, 1:02pm UTC](https://forum.ansible.com/t/how-to-get-a-sorted-list-of-the-last-n-files/22953 "2016-11-03T13:02:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Greg\_Langford](https://avatars.discourse-cdn.com/v4/letter/g/f1d935/32.png) [@Greg\_Langford](https://forum.ansible.com/u/Greg_Langford)\
**Post date:** [November 3, 2016, 1:02pm UTC](https://forum.ansible.com/t/how-to-get-a-sorted-list-of-the-last-n-files/22953/1 "2016-11-03T13:02:23Z")

</div>

Good Afternoon All,

I am looking for a way to get a list of files in a directory sorted by name.

At the moment I am using the command module to run ls on the remote system.

Is it possible with the find module to sort the results by the path?

This is how I am doing it at the moment [https://gist.github.com/greglangford/b9da158684f607687c3c867887f2d835](https://gist.github.com/greglangford/b9da158684f607687c3c867887f2d835)

Kind Regards

---

<div class="post-metadata">

**Author:** ![Kai\_Stian\_Olstad](https://avatars.discourse-cdn.com/v4/letter/k/e19adc/32.png) [@Kai\_Stian\_Olstad](https://forum.ansible.com/u/Kai_Stian_Olstad)\
**Post date:** [November 3, 2016, 4:17pm UTC](https://forum.ansible.com/t/how-to-get-a-sorted-list-of-the-last-n-files/22953/2 "2016-11-03T16:17:27Z")

</div>

> Good Afternoon All,
> 
> I am looking for a way to get a list of files in a directory sorted by name.
> 
> At the moment I am using the command module to run ls on the remote system.
> 
> Is it possible with the find module to sort the results by the path?

Not with find directly, but you can do when using the result.

> This is how I am doing it at the moment  
> [https://gist.github.com/greglangford/b9da158684f607687c3c867887f2d835](https://gist.github.com/greglangford/b9da158684f607687c3c867887f2d835)

tasks:  
&nbsp;&nbsp;&nbsp;- find: path=/tmp  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;register: files

&nbsp;&nbsp;&nbsp;- debug: msg="{{ item.path }}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;with\_items: "{{ (files.files | sort(attribute='path'))[-3:] }}"

---

<div class="post-metadata">

**Author:** ![Greg\_Langford](https://avatars.discourse-cdn.com/v4/letter/g/f1d935/32.png) [@Greg\_Langford](https://forum.ansible.com/u/Greg_Langford)\
**Post date:** [November 7, 2016, 8:42am UTC](https://forum.ansible.com/t/how-to-get-a-sorted-list-of-the-last-n-files/22953/3 "2016-11-07T08:42:38Z")

</div>

That's perfect just what I needed. Thank you so much.

Kind regards
