Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays &引用;推;bash关联数组_Arrays_Bash_Associative Array - Fatal编程技术网

Arrays &引用;推;bash关联数组

Arrays &引用;推;bash关联数组,arrays,bash,associative-array,Arrays,Bash,Associative Array,我正在尝试使用公共ID为目录中的所有文件运行脚本 ls-1*.vcf a1.sourceA.vcf a1.sourceB.vcf a1.sourceC.vcf a2.sourceA.vcf a2.sourceB.vcf a2.sourceC.vcf a3.sourceA.vcf a3.sourceC.vcf 在每种情况下,ID都位于第一个(a1、a2或a3)之前,对于每个ID,我希望将该ID的所有源放在关联数组中,由ID键入,例如: a1=>[a1.sourceA.vcf,a1.sourceB

我正在尝试使用公共ID为目录中的所有文件运行脚本

ls-1*.vcf

a1.sourceA.vcf
a1.sourceB.vcf
a1.sourceC.vcf
a2.sourceA.vcf
a2.sourceB.vcf
a2.sourceC.vcf
a3.sourceA.vcf
a3.sourceC.vcf
在每种情况下,ID都位于第一个
a1
a2
a3
)之前,对于每个ID,我希望将该ID的所有源放在关联数组中,由ID键入,例如:

a1
=>[
a1.sourceA.vcf
a1.sourceB.vcf
a1.sourceC.vcf
]

我尝试了以下方法:

for file in $(ls *.vcf | sort)
do
  id=$(echo $file | cut -d '.' -f 1)
  vcfs[$id]+=$file

done

for i in "${!vcfs[@]}"
do
  echo "key  : $i"
  echo "value: ${vcfs[$i]}"
  echo " "
done
但我不知道如何让它工作

在Perl中,我会将值推送到循环中数组的散列上:

push@{$vcfs{$id},$file

给我一个这样的数据结构:

  'a1' => [
            'a1.sourceA.vcf',
            'a1.sourceB.vcf',
            'a1.sourceC.vcf'
          ],
  'a3' => [
            'a3.sourceA.vcf',
            'a3.sourceC.vcf'
          ],
  'a2' => [
            'a2.sourceA.vcf',
            'a2.sourceB.vcf',
            'a2.sourceC.vcf'
          ]

如何在bash中实现这一点

来自问题评论中给出的另一个答案

unset a1 a2 a3

function push {
    local arr_name=$1
    shift
    if [[ $(declare -p "$arr_name" 2>&1) != "declare -a "* ]]
    then
        declare -g -a "$arr_name"
    fi
    declare -n array=$arr_name
    array+=($@)
}

for file in *.vcf; do [[ -e $file ]] && push "${file%%.*}" "$file"; done

(IFS=,;echo "${a1[*]}")
(IFS=,;echo "${a2[*]}")
(IFS=,;echo "${a3[*]}")
但是,根据需要,也许有模式就足够了

for file in a1.*.vcf; do ... ; done
最后,
$(ls)
不得在
for
循环中使用,如其他答案所示


它以
a3
停止,或者您有
a4
等等?@sjsam-任何数量的文件请参见。这是列表列表的答案,但您的解决方案将与之类似。@ccarton为您提供了答案。您可以使用关联数组,但我不打算回答这个问题,b/c您不想使用关联数组(每个键有一个值),而是使用散列数组。Bash不支持这一点,因此您需要围绕ccarton提供的大量工作。