bash script to alter array elements and write to new array

I would like a bash script to take the elements from array1 and output them differently in array2.

array1 –

array1=(s3://root/sub1/sub2/ 2022-10-22 2021-09-13 2020-08-15 s3://root/sub1/sub2/ 2022-09-22 2021-08-07 2020-02-03  s3://root/sub1/sub2/ 2022-08-22 2021-07-17 s3://root/sub1/sub2/ 2022-07-22)

array2-

array2=(s3://root/sub1/sub2/2022-10-22/ s3://root/sub1/sub2/2021-09-13/ s3://root/sub1/sub2/2020-08-15/ s3://root/sub1/sub2/2022-09-22/ s3://root/sub1/sub2/2021-08-07/ s3://root/sub1/sub2/2020-02-03/ s3://root/sub1/sub2/2022-08-22/ s3://root/sub1/sub2/2021-07-17/ s3://root/sub1/sub2/2022-07-22/)

So I basically want to take the url from array1 and append each date that follows it and store as a unique entry in array2.

My thought process is as follows – loop through array1 for each url entry write to new array and append the dates to that url that follow it from array1. I am unsure how to do this in bash however.

>Solution :

You’re looking for something like this:

array2=()
for elem in "${array1[@]}"; do
  if [[ $elem = s3:* ]]; then
    pfix=$elem
  else
    array2+=("$pfix$elem")
  fi
done

Leave a Reply