5

Every day I have to take backup and update the status to support teams at particular time for which I need to check last 5 lines of last created/modified *.aff file in a directory and update them.

Can anyone please let me know how to view last 5 lines from last modified file (particular extension) in linux as with *.aff file? other files are also created e.g. *.log, etc.

7

With the zsh shell:

tail -n 5 ./*.aff(D.om[1])

With other shells, it's quite difficult to come up with something reliable if you don't want to make assumptions on what file names may contain.

For instance, the bash equivalent, if you're on a recent GNU system would be:

find . -maxdepth 1 -name '*.aff' -type f -printf '%T@:%p\0' |
  sort -rzn |
  sed -zn 's/[^:]*://p;q' |
  xargs -r0 tail -n 5

Or:

find . -maxdepth 1 -name '*.aff' -type f -printf '%T@/%p\0' |
  sort -rzn | (IFS=/ read -rd '' mtime file && tail -n 5 "$file")
5

Assuming file names don't contain newline characters and that all the *.aff files are regular files:

ls -t1d -- *.aff | head -n 1

gives you the name of the most recently modified .aff-file. If you want the last 5 lines just do:

tail -n 5 -- "$(ls -t1d -- *.aff | head -n 1)"
  • @StéphaneChazelas Thank you for useful comments. Hope OP have not use file names started with -or .. Regarding -r I have miss that it isn't ls -l command which prints total in fist line. – Costas Nov 11 '14 at 15:50
0

Another safe approach that should work on any GNU system and Busybox:

tail -n5 "$(stat -c "%Y %n" ./* | 
    sort -nk1,1 | cut -d ' ' -f 2- | tail -n1)"

That will work on most things but if your file names can contain newlines, use this instead (GNU only, still breaks if your files end in newlines):

tail -n5 "$(stat --printf "%Y %n\0" ./* | 
    sort -rznk1,1 | sed -zn 's/[0-9]\+ //p;q')"
  • %X is last access time. That assumes a recent GNU system, that file names don't start with - or .. That they are all regular files. The second also assumes filename don't end in newline characters. – Stéphane Chazelas Nov 11 '14 at 16:25
  • @StéphaneChazelas thanks, I think I fixed everything but the final newline. sort -z is GNU also isn't it? – terdon Nov 11 '14 at 16:38
  • yes, supported since 1996. FreeBSD used to use GNU sort, it's now got a clone which also supports -z. It's GNU sed's -z that is recent (2012). – Stéphane Chazelas Nov 11 '14 at 16:58
  • @Costas OK, I prefer --printf because I want the \t but that seems to only work for GNU stat. Busybox stat also accepts -c though so you're right, that's more portable, thanks. It still fails on OSX (and presumably BSD) because their stat don't have --format or --printf (they need -f instead) but I can live with that. – terdon Nov 11 '14 at 18:27

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.