I am using
ls -t | head -8 to show the last 8 files modified in a directory, but this only prints the file name.
Is there a way to alter the above command so that it shows the modified date for the file names as well?
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.Sign up to join this community
You'll want to use
stat to get the file metadata:
stat -c $'%y\t%n' * | sort -n | head -8
stat is an easy way, but it can’t print the timestamp in a format like
ls -l. If you want more fine-grained control over the format, use
find with the
-printf option instead, e.g. for an (almost)
ls -l-like format:
find -maxdepth 1 -type f -printf "%T+#%Tb %Td %TH:%TM\t%p\n" | sort -rn | cut -d# -f2- | head -8
%T+ is needed to sort the output properly and gets removed by
cut aftwerwards. Read
man find to find out more about the
$ ls -l total 0 -rw-rw-r-- 1 dessert dessert 0 May 30 20:22 last week -rw-rw-r-- 1 dessert dessert 0 Jun 6 17:22 today -rw-rw-r-- 1 dessert dessert 0 Jun 5 17:22 yesterday $ stat -c $'%y\t%n' * | sort -n 2018-05-30 20:22:29.919608691 +0200 last week 2018-06-05 17:22:10.207084356 +0200 yesterday 2018-06-06 17:22:01.940284127 +0200 today $ find -maxdepth 1 -type f -printf "%T+#%Tb %Td %TH:%TM\t%p\n" | sort -rn | cut -d# -f2- Jun 06 17:22 ./today Jun 05 17:22 ./yesterday May 30 20:22 ./last week $ find -maxdepth 1 -type f -printf "%T+#%Tc\t%p\n" | sort -rn | cut -d# -f2- Wed 06 Jun 2018 05:22:01 PM CEST ./today Tue 05 Jun 2018 05:22:10 PM CEST ./yesterday Wed 30 May 2018 08:22:29 PM CEST ./last week $ find -maxdepth 1 -type f -printf "%T+\t%p\n" | sort -rn 2018-06-06+17:22:01.9402841270 ./today 2018-06-05+17:22:10.2070843560 ./yesterday 2018-05-30+20:22:29.9196086910 ./last week
ls command is not the most appropriate tool to use in this situation, as shown by other answers. There is a convoluted way to extract the information you want from the output of
ls, though it does have limitations. It's quite a good example of how working with
ls can quickly become complicated.
The specific issue with this chain of commands is that the use of the
tr command removes any multiple occurrences of whitespace and replaces with a single whitespace. This will affect filenames, making them unsuitable for parsing by a machine. Parsing ls is a discouraged activity generally though.
ls -lrt| tail -4| tr -s ' '| cut -d ' ' -f6-| tac
The reverse ordering of
ls results, with the
-r option, is used to avoid the 'Total' line output by the
-l option of
tac is used at the end to reorder the results after trimming away the unwanted output.