Array Numbering Elements - Bash Scripts
I have an array named c. Its members are the filenames found in the current directory. How can I list them on my line with the number before? For example:
1. aaa
2. filename2
3. bbb
4. asdf
The code I'm now printing is each file on a separate line. How:
aaa
filename2
bbb
asdf
My code is below:
#!/bin/bash
c=( $(ls --group-directories-first $*) )
printf '%s\n' "${c[@]}"
source to share
Starting with an array c
, there are three methods:
Using cat -n
The utility cat
will display the output lines:
$ cat -n < <(printf "%s\n" "${c[@]}")
1 aaa
2 filename2
3 bbb
4 asdf
Using bash
This method uses shell arithmetic for line numbers:
$ count=0; for f in "${c[@]}"; do echo "$((++count)). $f"; done
1. aaa
2. filename2
3. bbb
4. asdf
Using nl
In the comments, twalberg suggests using nl
:
$ nl < <(printf "%s\n" "${c[@]}")
1 aaa
2 filename2
3 bbb
4 asdf
The utility nl
has a number of options to control exactly how you want to number, including, for example, left / right alignment, including leading zeros. See man nl
.
source to share