从未知数量的外部列表创建数组

时间:2013-05-02 22:56:30

标签: arrays bash sed

这是另一个与从文本文件导入值相关的问题(类似于我之前的文件),但复杂性增加(我学习的bash脚本越多,它就越具挑战性)

目标:在每个外循环迭代中创建Day _....数组。假设不知道* .txt文件中存在多少Day _...列表,我试图这样做。

问题:目前我的内部循环只迭代一次(应该迭代为Monday上的元素数量。而且,我也使用my_sub_dom=$( sed 's/=.*//' weekly.txt )来获取列表数量/在weekly.txt中的数组,然后过滤包含Day的那些。

Bash脚本:

#!/bin/bash

source weekly.txt

declare -a my_sub_dom
day=( ${Monday[*]} )
my_sub_dom=$( sed 's/=.*//' weekly.txt ) # to construct a list of the number of of  lists in the text file
#echo "${my_sub_dom}"
counter=0
main_counter=0
for i in "${day[@]}"
do
    let main_counter=main_counter+1
    for j in "${my_sub_dom[@]}"
    do
    #       echo "$j"
            if grep -q "Day" "${my_sub_dom}"
            then
                    echo "$j"
                    sub_array_name="${my_sub_dom[counter]}" # storing the list name
                    sub_array_content=( ${sub_array_name[*]} )
                    echo "${sub_array_content}"
            else
                    echo "no"
            fi
            let counter=counter+1
    done
    echo "$counter"
    counter=0

完成 echo“$ main_counter”

文本文件格式:

Day_Mon=( "google" "yahoo" "amazon" )
Day_Tu=( "cnn" "msnbc" "google" )
Day_Wed=( "nytimes" "fidelity" "stackoverflow" )
Monday= ( "one" "two" "three" )
....

脚本输出:

grep: Day_Mon
Day_Tu
Day_Wed
Monday: No such file or directory
no
1
grep: Day_Mon
Day_Tu
Day_Wed
Monday: No such file or directory
no
1
grep: Day_Mon
Day_Tu
Day_Wed
Monday: No such file or directory
no
1
3

如果您需要任何其他信息,请告诉我。我非常感谢您对此事的任何意见,我已经尝试了几天了。

谢谢

1 个答案:

答案 0 :(得分:0)

给定一个包含

的文件weekly.txt
Day_Mon=( "google" "yahoo" "amazon" )
Day_Tu=( "cnn" "msnbc" "google" )
Day_Wed=( "nytimes" "fidelity" "stackoverflow" )
Monday=( "one" "two" "three" )

您可以遍历每个名​​为Day_的数组 - 使用

#!/bin/bash

# Set all arrays defined in the file
source weekly.txt

# Get all variables prefixed with "Day_" (bash 4)
for name in "${!Day_@}"
do
  echo "The contents of array $name is: "
  # Use indirection to expand the array
  arrayexpansion="$name[@]"
  for value in "${!arrayexpansion}"
  do
    echo "-- $value"
  done
  echo
done

这导致:

The contents of array Day_Mon is:
-- google
-- yahoo
-- amazon

The contents of array Day_Tu is:
-- cnn
-- msnbc
-- google

The contents of array Day_Wed is:
-- nytimes
-- fidelity
-- stackoverflow