Score:0

How do I print files in a directory with a numerical index preceding them?

in flag

I’d like to print all files in a directory with a numbering, so that each file has a number before it, like this:

  1. myfile.txt
  2. anotherfile
  3. etc

I then want to refer to these files later on, like this:

mv 1 2 3 directory

How could I refer to the files by a numerical ordering?

Score:0
hr flag

You could put the filenames in an indexed array, and use the array indices, ex.

shopt -s nullglob
files=( * )

for i in ${!files[@]}; do 
  printf '%d. %s\n' $i "${files[i]}"
done

To refer to a file via its index n, use "${files[n]}", where n is evaluated as a numeric expression, ex. "${files[3]}" or n=3; echo "${files[n]}". Note that array indices in bash start from 0.

in flag
What do ! and @ do, in the above?
hr flag
@PeterElbert `${files[@]}` expands to a list of array values; whereas `${!files[@]}` expands to a list of the array's indices (or keys, in the case of an associative array). See the `Arrays` subsection under the `PARAMETERS` section of `man bash`.
in flag
Thanks. Can I pass multiple indices to that file list? I’d like to conveniently move a bunch of files, like mv “${files[1, 2, 4:10, 22]}” directory. Or enter a live shell where I can just type “$ 1 2 4-10 directory”, without typing the “files”.
hr flag
@PeterElbert you'd need to write a custom move command (shell function) that maps its arguments back to filenames I think (there's no way for the shell - or mv - to know that `1`, `2` and `4-10` are not filenames)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.