I have a dir in

My main DIR is /tmp/folder

Inside /tmp/folder there are is a X number of folders only (not files). For example


Inside these folders the are many files of same extension. I want from every one of these folder, to get the last & first created files (modifitied time).

The output i prefer to be like this


I will parse this output using a script, so you can do any output you want, but please do it in a friendly way so i can parse it easily.

The bash command should be only 1

  • "The bash command should be only 1" Please explain. – RobertL Nov 7 '15 at 16:58
find "$DIR" -type d | while read d; do echo "$d,$(ls -t "$d" | sed -n '1h; $ { G; s/\n/,/g; p }')"; done

Or, in more readable format and using an extra variable for demonstration:

find "$DIR" -type d |
while read d;
    files=$(ls -t "$d" | sed -n '1h; $ { G; s/\n/,/g; p }')
    printf '%s,%s\n' "$d" "$files";

This finds all subdirectories of $DIR using the find command. For each one found, uses ls -tr to get a list of files in that directory sorted by date, newest first.

Pipe the output of ls -tr into sed joining the first and last line with a comma: Option -n suppresses the default output, 1h saves the first line (newest filename) in the hold space, and at the last line of the file (selected by $) appends the hold space (newest filename) with H to the pattern space (delimited by a newline), and changes that newline to a comma.

The script then printfs the subdirectory name followed by a comma, followed by the files that came out of sed.

This makes no distinction between directories and files for oldest/newest selection, so if you don't want directories there, you'll need to filter the output of ls -t to remove the directories.

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.