[英]concatenate variable into single variable separated by comma with for loop
[英]How to combine for loop values in one variable separated by comma [unix scripting]
我有这个值: 123456
和修剪最后一位数字的 for 循环:
第一次迭代: 123456
第二次迭代: 12345
第三次迭代: 1234
第四次迭代: 123
第 5 次迭代: 12
第 6 次迭代: 1
我希望将输出存储在一个变量中
像这样: varA = 123456,12345,1234,123,12,1
像这样: varB = '123456','12345','1234','123','12','1'
这是我的代码:
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
for循环之前:
allinput=
for循环内部:
allinput+="'${input}',"
for循环后:
allinput=${allinput%,}
使用子串:
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}"
使用算术:
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}"
一种方法是利用数组,并使用${foo[*]}
扩展将数组转换为单个字符串,其中元素由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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.