【发布时间】:2013-06-13 02:32:04
【问题描述】:
我正在尝试使用目录中所有文件的文件名和另一个整数创建一个哈希表。像“文件名”:“数字”。代码应该在 bash 4.x 中。这是我写的代码:
#!/bin/bash
DIR=`ls`
declare -A ARRAY
ZERO=0
for FILES in $DIR
do
echo "We have $FILES"
ARRAY+=(["$FILES"]="$ZERO")
done
echo "Done with filling up array!"
for file in "${ARRAY[@]}" ; do
KEY="${file%%:*}"
VALUE="${file##*:}"
printf "%s has number %s.\n" "$KEY" "$VALUE"
done
echo "We are done here!"
echo "Check: "
printf "%s has the number %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"
它给出了这个输出:
[Anil@computer68 test]$ bash kenzo.sh
bash kenzo.sh
We have dafuq.sh
We have hello.cpp
We have kenzo.sh
Done with filling up array!
0 has number 0.
0 has number 0.
0 has number 0.
We are done here!
Check:
has the number
我该如何解决?哈希表中的所有元素都没有文件名和编号的任何值。
【问题讨论】:
-
不要解析
ls的内容。使用DIR=*,或直接使用for files in *。
标签: bash shell dictionary hashtable associative-array