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[@]}"

      

+3


source to share


2 answers


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

.

+1


source


This should work:



for (( i=0; i<${#c[@]}; i++)); do
printf '%d. %s\n' $((i+1)) "${c[$i]}"
done

      

+1


source







All Articles