0

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

/tmp/folder/1
/tmp/folder/2
/tmp/folder/3
/tmp/folder/4
/tmp/folder/5

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

/tmp/folder/1,OLD_FILE,NEW_FILE
/tmp/folder/2,OLD_FILE,NEW_FILE
/tmp/folder/3,OLD_FILE,NEW_FILE
/tmp/folder/4,OLD_FILE,NEW_FILE
/tmp/folder/5,OLD_FILE,NEW_FILE

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

OhGodWhy
  • 115
  • 3
  • 12

1 Answers1

3
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;
do
    files=$(ls -t "$d" | sed -n '1h; $ { G; s/\n/,/g; p }')
    printf '%s,%s\n' "$d" "$files";
done

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.

Philippos
  • 13,453
RobertL
  • 6,780