I have multiple sub-directories (which are named using GUIDs), which contain results files from computer simulations that I have been running. The files are all named in the following way: hydro_configuration_xxxx.xyz, where xxxx is a four-digit number from 0000 upwards; the latest file has the highest four-digit number. I would like to be able to list the latest file in each subdirectory, along with the directory that it is in.

So, for example, given sub-directory fc86783b-bcc5-4456-8964-049682ee81aa containing files hydro_configuration_0000.xyz to hydro_configuration_0123.xyz, and directory e608273d-35bd-442c-9de1-0ec184aa0d95 containing files hydro_configuration_0000.xyz to hydro_configuration_3564.xyz, I need a command that produces the output:

  • A helpful user left an answer but deleted it before I could accept. The following command gave me the output that I needed: find n512/ -type d | while read d; do ls -ltr $d/hydro* | tail -n 1; done |awk -F " " '{print $8}' >out.txt – endian Oct 12 '11 at 12:33

Create bash script latestfile.sh with the following content:

ls -1tr "$1" | tail -n1

Run chmod +x latestfile.sh to make it executable.

Then execute the following command:

find test -mindepth 1 -type d -name "hydro_configuration_*" -printf "%p/" -a -exec ./latestfile.sh {} \;

This will find all directories matching the pattern and print their names followed by a /, followed by the name of the latest file in there.

  • Thanks, I actually used an alternative approach but I'm sure yours would work as well. Since the original user who helped me deleted his answer, I will accept yours instead! – endian Oct 12 '11 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.