3

Say i have the following command. It's set to display a list of the last 20 files modified on my drive with the paths included.

find -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r | head -20

The command works fine however in the format of the date and time there is too much information as it also displays the milliseconds. My questions were how would I remove this. In addition, how could I change the position it prints in so that the path would show up on the left side and the date on the right?

5

You could do this:

find -type f -printf '%TY-%Tm-%Td %.8TT %p\n' | sort -r | sed -r 's/(^[^ ]+ [^ ]+) (.+)/\2 \1/' | head -20

Putting .8 between % and TT modifies that field to limit it to 8 characters (hh:mm:ss). The sed regex moves the first part of the line (to sets of non-space characters with one space between) to the end of the line. It's necessary for the time to be at the beginning of the line for the sort command.

Warning: Putting the date after the file name could potentially cause confusion if filenames are displayed that contain spaces and numbers. However, for viewing as a human rather that for feeding into another script or program, this output should be fine.

Otherwise, to leave the times in front of the filenames:

find -type f -printf '%TY-%Tm-%Td %.8TT %p\n' | sort -r | head -20

EDIT: sed is unnecessary for trimming fractional second per @steeldriver's comment. This may be a GNU extension, but -printf doesn't appear to be POSIX anyway. Also, corrected sorting bug.

3
  • Hi. Thank you so much for your help. The layout is as i wanted however putting the text before the date seems to cause issues so i think i may leave that part out. However, when i keep the command as in my original while ONLY adding the sed regex it doesn't seem to remove the additional numerals (milliseconds). Why could this be ? – flowoftruth Dec 21 '14 at 2:29
  • 2
    At least with the GNU version of find, you can specify a precision for the time field e.g. to print exactly 8 characters hh:mm:ss (omitting the fractional seconds), replace %TT by %.8TT – steeldriver Dec 21 '14 at 2:44
  • @flowoftruth Fixed. – depquid Dec 21 '14 at 3:20

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.