5

I am using

ls -ltr /homedir/mydirectory/work/ |tail -n 1|cut -d ' ' -f 10

But this is a very crude way of getting the desired result.And also its unreliable. The output I get on simply executing

ls -ltr /homedir/mydirectory/work/ |tail -n 1

is

-rw-r--r-- 1 user pusers 1764 Apr  1 12:06 firstfile.xml

So here I get the file name. But if the output on doing the above command is like

-rw-r--r-- 100 user pusers 1764 Apr  1 12:06 firstfile.xml

the first command fails ! And understandably as I am cutting the result from the 10th character which does not hold valid now.

So how to refine it.

2
  • Does "latest" mean the file of which the modification date is the most recent?
    – user529758
    Commented Apr 2, 2013 at 5:58
  • 1
    Yes. it means that. I want the file name alone
    – R11G
    Commented Apr 2, 2013 at 6:03

3 Answers 3

10

Why do you use the -l flag for ls if you don't need it? Make ls simply output the filenames if you don't need more information instead of trying to "parse" its non-unified output (raping poor text processing utilities...).

LAST_MODIFIED_FILE=`ls -tr | tail -n 1`
4
  • But I want the filename. Thats the requirement. So, got to use the "cut"
    – R11G
    Commented Apr 2, 2013 at 6:11
  • 2
    @R11G Nah, you don't. What do you think ls outputs if not filenames, seriously? Have you even tried the solution I proposed at all?
    – user529758
    Commented Apr 2, 2013 at 6:12
  • Yes. I tried that only. The confusion I still have is like if the second column (hard link count to that file/directory) is in two/three digits - my earlier command where I am using 'cut' to get ONLY the file name - will fail. How to overcome that?
    – R11G
    Commented Apr 2, 2013 at 6:23
  • @R11G If all you need is the filename, then my code will work.
    – user529758
    Commented Apr 2, 2013 at 6:24
1

If you really want to achieve this using your method, then, use awk instead of cut

ls -ltr /var/log/ |tail -n 1| awk '{print $9}'
1

Extended user user529758 answer which can give result as per file name

use below commnad as per the file name

ls -tr Filename* | tail -n 1

Not the answer you're looking for? Browse other questions tagged or ask your own question.