Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am looking to display the 8th file name in a directory using ls -l and pipe for example ls -l | wc -1 would give me the count but what i want to have returned is the 8th file name in the directory list whatever it is. i have looked at grep and wildcards but still do not see which command would give me the result i am looking for.

Thanks

share|improve this question

3 Answers 3

try

ls -l | head -n 9 | tail -n 1

if you want only name you can use cut at the end

ls -l | head -n 9 | tail -n 1 | tr -s ' ' | cut -d' ' -f8

tr is to replace multiply spaces and tabs by one space

share|improve this answer
    
awesome thank you very much –  Erich May 24 '12 at 19:47
    
+1 for the tr -s ' ' | cut trick, I never thought of that for some reason - i typically use (g)awk when extracting columns. –  Rich Homolka May 24 '12 at 20:30
1  
If the filename contains multiple spaces in sequence, the returned file name will be wrong by having its spaces collapsed. And for that matter, even if the filename just contains a single space, it will not be returned in full since only field 8 is returned, which is the file name up to its first space. Also, you don't need ls -l as pointed out if you just want the filename, but you also don't even need ls -1; just ls will do (see superuser.com/q/424246/49184). –  Daniel Andersson May 25 '12 at 7:10
1  
This also gives the wrong output on my system, since it is dependent on the lcoale for the date format. -f9 is needed here (as also touched upon in cokedude's answer), but as I said, file names with spaces will be incorrect. -f9- will return fields 9 and onwards and be better, but then again, file names with multiple spaces in sequence will still be wrong. –  Daniel Andersson May 25 '12 at 7:15

Another way is like this.

ls -l | sed -n '9p'

If you only want the file or directory name then use this.

ls -l | sed -n '9p' | awk '{print $9}'

jcubic are you sure this is what you wanted?

ls -l | head -n 9 | tail -n 1 | tr -s ' ' | cut -d' ' -f8

I would think he would want the file or directory name like this.

ls -l | head -n 9 | tail -n 1 | tr -s ' ' | cut -d' ' -f9

share|improve this answer
ls | awk 'NR==8'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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