我想编写一个函数,它采用数组变量名并更新内容。例如:
ARRAY1=("test 1" "test 2" "test 3")
toUpper ARRAY1
for arg in "${ARRAY1[@]}"; do
echo "arg=$arg"
done
# output
arg=TEST 1
arg=TEST 2
arg=TEST 3
我对此进行了粗略的尝试,这需要输入数组的副本。使用间接引用,我可以创建输入变量的副本。数组的副本用于获取元素的计数。如果有更好的方法来做到这一点,请告诉我。
function toUpper() {
local ARRAY_NAME=$1
local ARRAY_REF="$ARRAY_NAME[@]"
# use an indirect reference to copy the array so we can get the count
declare -a ARRAY=("${!ARRAY_REF}")
local COUNT=${#ARRAY[@]}
for ((i=0; i<$COUNT; i++)); do
local VAL="${ARRAY[$i]}"
VAL=$(echo $VAL | tr [:lower:] [:upper:])
echo "ARRAY[$i]=\"$VAL\""
eval "$ARRAY_NAME[$i]=\"$VAL\""
done
}
ARRAY1=( "test" "test 1" "test 3" )
toUpper ARRAY1
echo
echo "Printing array contents"
for arg in "${ARRAY1[@]}"; do
echo "arg=$arg"
done
Using bash 4.3+你可以做
arr=( "test" "test 1" "test 3" )
toUpper() { declare -n tmp="$1"; printf "%s\n" "${tmp[@]^^}"; }
toUpper arr
TEST
TEST 1
TEST 3
Update:为了反映原始数组的变化:
toUpper() {
declare -n tmp="$1";
for ((i=0; i<"${#tmp[@]}"; i++)); do
tmp[i]="${tmp[i]^^}"
done;
}
arr=( "test" "test 1" "test 3" )
toUpper arr
printf "%s\n" "${arr[@]}"
TEST
TEST 1
TEST 3
Update2:这是一种让它工作的方法较旧的 BASH(4 之前)版本不带eval
:
upper() {
len=$2
for ((i=0; i<len; i++)); do
elem="${1}[$i]"
val=$(tr '[:lower:]' '[:upper:]' <<< "${!elem}")
IFS= read -d '' -r "${1}[$i]" < <(printf '%s\0' "$val")
done;
}
arr=( "test" "test 1" "test 3" )
upper arr ${#arr[@]}
printf "%s\n" "${arr[@]}"
TEST
TEST 1
TEST 3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)