Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbering Array Elements - Bash Scripting

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[@]}"
like image 410
JRM1201 Avatar asked Aug 05 '26 13:08

JRM1201


2 Answers

Starting with array c, here are three methods:

Using cat -n

The cat utility will number output lines:

$ cat -n < <(printf "%s\n" "${c[@]}")
     1  aaa
     2  filename2
     3  bbb
     4  asdf

Using bash

This 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

Using nl

In 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.

like image 83
John1024 Avatar answered Aug 08 '26 20:08

John1024


This should work:

for (( i=0; i<${#c[@]}; i++)); do
printf '%d. %s\n' $((i+1)) "${c[$i]}"
done
like image 28
Jahid Avatar answered Aug 08 '26 20:08

Jahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!