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

2
  • 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? Commented Jun 11, 2019 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. Commented Jun 11, 2019 at 15:53

2 Answers 2

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.

4
  • 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. Commented Jun 11, 2019 at 15:56
  • Hmm, didn't return anything for me Commented Jun 11, 2019 at 15:58
  • Make sure you replace $fileIndex with the actual index (i.e. 2) of the file you're trying to find. Commented Jun 11, 2019 at 16:03
  • I know, replace the single quotes with double quotes and it works fine Commented Jun 11, 2019 at 16:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.