3

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[@]}"
4
  • Have you attempted anything for this? Commented Apr 27, 2015 at 20:04
  • You asked about numbering arrays, not creating them, but the creation part deserves comment: c=( $(ls --group-directories-first $*) ) will lead to problems if any of your files have whitespace in their names. Commented Apr 27, 2015 at 20:13
  • I see that now @John1024, thanks for mentioning that. Any idea how I can fix that? Commented Apr 27, 2015 at 20:36
  • The simplest is c=( * ). This will create an array with all file names and is safe to use whatever characters are in the file names. This does approach, however, does not offer the --group-directories-first functionality. Commented Apr 27, 2015 at 20:41

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

nl is a useful alternative to cat -n that has a number of options for controlling exactly how you want the numbering done...
Thanks John1024, I used bash (the second method) to fix it and it worked perfectly.
@twalberg, Excellent suggestion. I added nl to the answer. JRM1201, glad it worked for you.
1

This should work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.