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.



4 Answers 4



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

  • +1 for the tr -s ' ' | cut trick, I never thought of that for some reason - i typically use (g)awk when extracting columns. May 24, 2012 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). May 25, 2012 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. May 25, 2012 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

ls | awk 'NR==8'

Just don't use -l

ls | head -8 | tail -1

You get file name, ls orders files same as ls -l.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .