![](/img/trans.png)
[英]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.