Results 1 to 8 of 8
I'm trying to return the latest edited file from an ls command. What I get from:
Code:
ls -ltr filename.* | awk {'print $NF'}
is a list of the filenames ...
- 11-21-2007 #1
[SOLVED] Only return one item from ls
I'm trying to return the latest edited file from an ls command. What I get from:
is a list of the filenames only in order. How do I get just the final file?Code:ls -ltr filename.* | awk {'print $NF'}Linux User #453176
- 11-21-2007 #2Linux Enthusiast
- Join Date
- Aug 2006
- Posts
- 631
Something like this?
RegardsCode:ls -ltr filename.* | head -1| awk '{print $NF}'
- 11-21-2007 #3
Perfect! But that returns the top item so not reversing the results is what I needed:
ThanksCode:ls -lt filename.* | head -1| awk '{print $NF}'Linux User #453176
- 11-21-2007 #4Linux Enthusiast
- Join Date
- Aug 2006
- Posts
- 631
Did you use the -r option e.g. ls -ltr?
Instead of that you can use tail -1.
or:Code:ls -ltr filename.* | head -1| awk '{print $NF}'
RegardsCode:ls -lt filename.* | tail -1| awk '{print $NF}'
- 11-21-2007 #5
If you want the most recently modified file:
With zsh:Code:ls -t|head -n1
For the oldest:Code:print *(om[1])
Code:ls -tr|head -n1
Code:print *(Om[1])
- 11-21-2007 #6
What I wanted was to grep all the files for a string and then get the latest edited filename with that string. I've done this by:
Code:for i in `ls -tx`; do for j in `grep -l MYSTRING *`; do if [[ $j == $i ]] ; then echo $j; fi ; done; done | head -1 | xargs grep MYSTRING | xargs echo String:
Linux User #453176
- 11-21-2007 #7
That seems needlessly complex. This works for me:
Code:ls -t $(grep -l MYSTRING *) | head -1
--
Bill
Old age and treachery will overcome youth and skill.
- 11-24-2007 #8Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
A common mistake people make when using ls in a pipeline is to not realise that it puts the names out one per line if it's not writing to the screen (try it with "ls | cat" if you need proof) so they persist in using long listing and have to strip off all the redundant characters. You can also force ls to write one per line to the screen with the -1 (digit one) flag.
It's always worth reading the man page for any command you're using to see if it already provides something useful (you can bet you're probably not the first person to have your specific requirement!).


