0

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

Oliver Salzburg
  • 86,445
  • 63
  • 260
  • 306
Erich
  • 1
  • 1

4 Answers4

4

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

jcubic
  • 2,833
  • 2
  • 23
  • 23
  • +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 http://superuser.com/q/424246/49184). – Daniel Andersson May 25 '12 at 07: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 07:15
1

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

cokedude
  • 419
  • 1
  • 4
  • 9
0
ls | awk 'NR==8'
Daniel Andersson
  • 23,895
  • 5
  • 57
  • 61
0

Just don't use -l

ls | head -8 | tail -1

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