I have an array named c. Its elements are filenames found in the current directory. How do I list them on their own line with a number before? For example:
1. aaa
2. filename2
3. bbb
4. asdf
The code I have now just prints each file on its own line. Like:
aaa
filename2
bbb
asdf
My code is below:
#!/bin/bash
c=( $(ls --group-directories-first $*) )
printf '%s\n' "${c[@]}"
Starting with array c, here are three methods:
cat -nThe cat utility will number output lines:
$ cat -n < <(printf "%s\n" "${c[@]}")
1 aaa
2 filename2
3 bbb
4 asdf
bashThis method uses shell arithmetic to number the lines:
$ count=0; for f in "${c[@]}"; do echo "$((++count)). $f"; done
1. aaa
2. filename2
3. bbb
4. asdf
nlIn the comments, twalberg suggests the use of nl:
$ nl < <(printf "%s\n" "${c[@]}")
1 aaa
2 filename2
3 bbb
4 asdf
The utility nl has a number of options for controlling exactly how you want the numbering done including, for example, left/right justification, inclusion of leading zeros. See man nl.
This should work:
for (( i=0; i<${#c[@]}; i++)); do
printf '%d. %s\n' $((i+1)) "${c[$i]}"
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With