0

Using bash, I need to be able to find a file in a specific position when listed alphabetically. For example, if I had the files a, b, c, d, e in a directory, and I wanted to find the third file, I would need it to return c. If I wanted the 5th file, it would return e.

Thanks for any help, sorry if this is phrased poorly, I'll rephrase it later if I can think of a way

  • should this work recursively, and if so, how does the counting play into that? do you only want files or would directories count? what if there isn't a (say) 5th file? – Jeff Schaller Jun 11 at 15:49
  • If asked for a 5th file, there would be a 5th file. There also won't be any directories to worry about. – Dragon8oy Jun 11 at 15:53
3

With zsh:

printf '%s\n' *([5])

Gives you the 5th non-hidden file in lexical order. Change to *(D[5]) to include hidden files (note that . and .. are never included).

In any Bourne-like shell, you can do the same with:

set -- *
printf '%s\n' "$5"
-2

This work in any shell: ls | awk "NR==$fileIndex{ print; }"

Explanation:

ls returns all the files in a directory in alphabetical order, and piping ls runs each file on its own newline, and awk "NR==$fileIndex{ print; }" will print the line number defined by $fileIndex.

  • 2 points: 1) don't parse ls; 2) the bash variable won't expand inside single quotes -- pass the variable with awk's -v option. – glenn jackman Jun 11 at 15:56
  • Hmm, didn't return anything for me – Dragon8oy Jun 11 at 15:58
  • Make sure you replace $fileIndex with the actual index (i.e. 2) of the file you're trying to find. – Dr-Bracket Jun 11 at 16:03
  • I know, replace the single quotes with double quotes and it works fine – Dragon8oy Jun 11 at 16:21
  • Fixed, thanks :P – Dr-Bracket Jun 11 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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