我有一个包含重复项的数组,例如
THE_LIST=(
"'item1' 'data1 data2'"
"'item1' 'data2 data3'"
"'item2' 'data4'"
)
基于上述,我想创建一个关联数组,将其分配itemN
为键和dataN
值。
我的代码遍历列表,并像这样分配key =>值(附加功能被缩短,因为它在列表上执行一些附加工作):
function get_items(){
KEY=$1
VALUES=()
shift $2
for VALUE in "$@"; do
VALUES[${#VALUES[@]}]="$VALUE"
done
}
declare -A THE_LIST
for ((LISTID=0; LISTID<${#THE_LIST[@]}; LISTID++)); do
eval "LISTED_ITEM=(${THE_LIST[$LISTID]})"
get_items "${LISTED_ITEM[@]}"
THE_LIST=([$KEY]="${VALUES[@]}")
done
当我打印数组时,我得到类似的东西:
item1: data1 data2
item1: data2 data3
item2: data4
但是,我想得到:
item1: data1 data2 data3
item2: data4
无法找到合并重复键以及删除重复值的方法。
这里的方法是什么?
更新
实际的代码是:
THE_LIST=(
"'item1' 'data1 data2'"
"'item1' 'data2 data3'"
"'item2' 'data4'"
)
function get_backup_locations () {
B_HOST="$2"
B_DIRS=()
B_DIR=()
shift 2
for B_ITEM in "$@"; do
case "$B_ITEM" in
-*) B_FLAGS[${#B_FLAGS[@]}]="$B_ITEM" ;;
*) B_DIRS[${#B_DIRS[@]}]="$B_ITEM" ;;
esac
done
for ((B_IDX=0; B_IDX<${#B_DIRS[@]}; B_IDX++)); do
B_DIR=${B_DIRS[$B_IDX]}
...do stuff here...
done
}
function get_items () {
for ((LOCIDY=0; LOCIDY<${#LOCATIONS[@]}; LOCIDY++)); do
eval "LOCATION=(${LOCATIONS[$LOCIDY]})"
get_backup_locations "${LOCATION[@]}"
THE_LIST=([$B_HOST]="${B_DIR[@]}")
done | sort | uniq
}
使用以下命令打印数组时:
for i in "${!THE_LIST[@]}"; do
echo "$i : ${THE_LIST[$i]}"
done
我懂了
item1: data1 data2
item1: data2 data3
item2: data4
如果保证键和值是纯字母数字的,则可能会执行以下操作:
declare -A output
make_list() {
local IFS=" "
declare -A keys # variables declared in a function are local by default
for i in "${THE_LIST[@]}"
do
i=${i//\'/} # since everything is alphanumeric, the quotes are useless
declare -a keyvals=($i) # split the entry, filename expansion isn't a problem
key="${keyvals[0]}" # get the first value as the key
keys["$key"]=1 # and save it in keys
for val in "${keyvals[@]:1}"
do # for each value
declare -A "$key[$val]=1" # use it as the index to an array.
done # Duplicates just get reset.
done
for key in "${!keys[@]}"
do # for each key
declare -n arr="$key" # get the corresponding array
output["$key"]="${!arr[*]}" # and the keys from that array, deduplicated
done
}
make_list
declare -p output # print the output to check
使用示例输入,我得到以下输出:
declare -A output=([item1]="data3 data2 data1" [item2]="data4" )
数据项乱序,但已删除重复数据。
最好将Python与csv
模块一起使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句