Home > Net >  How to combine for loop values in one variable separated by comma [unix scripting]
How to combine for loop values in one variable separated by comma [unix scripting]

Time:11-02

I have this value: 123456

and a for loop that trims the last digit:

1st iteration: 123456

2nd iteration: 12345

3rd iteration: 1234

4th iteration: 123

5th iteration: 12

6th iteration: 1

i would like the output to be stored in one variable

like this: varA = 123456,12345,1234,123,12,1

and like this: varB = '123456','12345','1234','123','12','1'

here's my code:

export input=$1
length=${#input}
j="$input"

for (( i=1, j=0; i<=length; i  , j=j 1 )); do
  len=$(echo "$((length-$j))")
  eachinput=$(echo ${input:0:$len})
  echo "each input : "$eachinput              #displays each trimmed value
done

CodePudding user response:

before for loop:

allinput=

inside of for loop:

allinput ="'${input}',"

after for loop:

allinput=${allinput%,}

CodePudding user response:

Using substrings:

store_number_prefixes() {
  local -ir input="$1"
  local -n outputA="$2" outputB="$3"
  local slice
  local -i i
  outputA="$input"
  outputB="'${input}'"
  for ((i = -1; i > -${#input}; --i)); do
    slice="${input::i}"
    outputA =",${slice}"
    outputB =",'${slice}'"
  done
}

store_number_prefixes 123456 varA varB

echo "varA = ${varA}"
echo "varB = ${varB}"

Using arithmetics:

store_number_prefixes() {
  local -i input="$1"
  local -n outputA="$2" outputB="$3"
  outputA="$input"
  outputB="'${input}'"
  for ((input /= 10; input; input /= 10)); do
    outputA =",${input}"
    outputB =",'${input}'"
  done
}

store_number_prefixes 123456 varA varB

echo "varA = ${varA}"
echo "varB = ${varB}"

CodePudding user response:

One way is to leverage arrays, and using ${foo[*]} expansion to turn an array into a single string with elements separated by the value of IFS:

#!/usr/bin/env bash

# Add commas between elements of the array name given as the argument
commafy() {
    local -n arr="$1" # Nameref
    local IFS=,
    printf "%s\n" "${arr[*]}"
}

# Add quotes around elements and commas between the elements of the
# array name given as the argument.
# Note: Will break with spaces in array elements
quote_and_commafy() {
    local -n arr="$1"
    local -a quoted=( $(printf "'%s'\n" "${arr[@]}") )
    local IFS=,
    printf "%s\n" "${quoted[*]}"
}

input=123456
components=()

for (( i = ${#input}; i > 0; i-- )); do
    components =(${input:0:i})
done

varA=$(commafy components)
varB=$(quote_and_commafy components)

printf "%s\n" "$varA" "$varB"
  • Related