我有這個價值: 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
uj5u.com熱心網友回復:
for回圈之前:
allinput=
for回圈內部:
allinput ="'${input}',"
for回圈后:
allinput=${allinput%,}
uj5u.com熱心網友回復:
使用子串:
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}"
uj5u.com熱心網友回復:
一種方法是利用陣列,并使用${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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/344999.html
下一篇:使用變數索引
