Search code examples
arraysbash

BASH - Convert array to list


i need convert an array to list and wrtiting in a file, but the result is without space or delimiter, eg:

 declare -a INSTANCEID=`ec2-run-instances --instance-count 2 --key xxx --instance-type t2.micro [...] ${AMIID} | ./getInstanceId.pl -`

if i make an echo of INSTANCEID i have i-75bxxxfai-72bxxxfd. How can separate the two values (i-75bxxxfa and i-72bxxxfd) and writing in a file, one per lines?

I have tried with:

printf "%s\n"  "${INSTANCEID[@]}" > file.txt

but i have always the same output


Solution

  • As per the comments over in the question description, OP wants to strip a string carrying instances.

    A portable bash logic for this would be something like below. The below statements can be just run in command line.

    $ INSTANCEID=i-75bxxxfai-72bxxxfd
    $ IFS="-" read -ra instances <<<"$INSTANCEID"
    
    $ for (( i=1; i<=$(( ${#instances[*]} -1 )); i++ )); \
        do printf "%s\n" "${instances[0]}-${instances[$i]//i} "; done
    

    This will print the individual instances as

    i-75bxxxfa
    i-72bxxxfd
    

    The idea here is

    • Split the input string from $INSTANCEID variable with de-limiter as - and read them into an array(read command with -a for array-read operation). The array contains entries as i, 75bxxxfai, 72bxxxfd
    • Now looping over the array instances over the total count "${#instances[*]}" - 1 and forming the string as "${instances[$0]}-${instances[$i]//i}" which is the string i followed by de-limiter - and the subsequent elements of the array with i removed ("${instances[$i]//i}")

    You can see it working for any number of strings with multiple instance id's as:-

    With 3 instances

    $ INSTANCEID=i-75bxxxfai-72bxxxfdi-72bxxxfdi
    $ IFS="-" read -ra instances <<<"$INSTANCEID"
    
    $ for (( i=1; i<=$(( ${#instances[*]} -1 )); i++ )); \
        do printf "%s\n" "${instances[0]}-${instances[$i]//i} "; done
    
    i-75bxxxfa
    i-72bxxxfd
    i-72bxxxfd
    

    With 4 instances

    $ INSTANCEID=i-75bxxxfai-72bxxxfdi-72bxxxfdii-7894xxuk
    $ IFS="-" read -ra instances <<<"$INSTANCEID"
    
    $ for (( i=1; i<=$(( ${#instances[*]} -1 )); i++ )); \
        do printf "%s\n" "${instances[0]}-${instances[$i]//i} "; done
    
    i-75bxxxfa
    i-72bxxxfd
    i-72bxxxfd
    i-7894xxuk
    

    Read more about bash- Shell Parameter Expansion