# fetch the newest file in a directory.

**URL:** <https://forum.ansible.com/t/fetch-the-newest-file-in-a-directory/23588>\
**Category:** Ansible Project\
**Created:** [January 29, 2017, 6:25pm UTC](https://forum.ansible.com/t/fetch-the-newest-file-in-a-directory/23588 "2017-01-29T18:25:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Scuderia\_FormulaOne](https://avatars.discourse-cdn.com/v4/letter/s/ecae2f/32.png) [@Scuderia\_FormulaOne](https://forum.ansible.com/u/Scuderia_FormulaOne)\
**Post date:** [January 29, 2017, 6:25pm UTC](https://forum.ansible.com/t/fetch-the-newest-file-in-a-directory/23588/1 "2017-01-29T18:25:36Z")

</div>

I would like to get the most recent file, in a specific directory, from remote nodes:

I am thinking about running a command similar to:

ls -lrt /tmp/backup |tail -1 | awk '{print $9}

then putting the results of that in the fetch command.

Any suggestions? Does this seem like a good path?

---

<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:** [January 30, 2017, 3:35pm UTC](https://forum.ansible.com/t/fetch-the-newest-file-in-a-directory/23588/2 "2017-01-30T15:35:52Z")

</div>

I think this is you only option since Ansible doesn't have any modules to do this, but you can make it a little shorter by removing -l.

ls -t /tmp/backup | head -1  
or  
ls -tr /tmp/backup | tail -1

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [January 30, 2017, 4:15pm UTC](https://forum.ansible.com/t/fetch-the-newest-file-in-a-directory/23588/3 "2017-01-30T16:15:19Z")

</div>

You can do 2 steps, first run the find module in that directory, then using the map filter, sort by mtime and use the `last` filter to get the most recent file.
