0

Given an array in Bash, is there a simple and efficient way to prepend numbers for each element sequentially?

Note: Adding commas bellow just to make arrays more readable!

Example, given:

my_array=(a, b, c, d, e)

Desired as result:

my_array=(1, a, 2, b, 3, c, 4, d, 5, e)

Or getting lines from a command result, where every line would be an element, have a number prepended before each item:

readarray -t my_array < <(my_command)

If there was a way to expand the array indexes along with the elements it would work for what I need, but I didn't found anything like this.

2
  • Is you intention to have comma in array elements? but I didn't found anything like this. Really? Commented Nov 10, 2020 at 22:50
  • @KamilCuk No, no comma. I just added the comma to make it more visible. Commented Nov 11, 2020 at 7:33

1 Answer 1

4

The obvious solution should be fast:

my_array=(a, b, c, d, e)  tmp=()
for ((i=0;i<${#my_array[@]};++i)); do
   tmp+=("$((i+1))," "${my_array[i]}")
done
my_array=("${tmp[@]}")
declare -p my_array
# would output:
# declare -a my_array=([0]="1," [1]="a," [2]="2," [3]="b," [4]="3," [5]="c," [6]="4," [7]="d," [8]="5," [9]="e")

If the , behind numbers is not relevant, you may use a neat trick with sed in your readarray command:

readarray -t my_array < <(printf "%s\n" "${my_array[@]}" | sed =)
Sign up to request clarification or add additional context in comments.

1 Comment

Or, iterate over the array indices: for i in "${!my_array[@]}"

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.