0

这是另一个与从文本文件中导入值相关的问题(类似于我以前的一个),但增加了复杂性(我对 bash 脚本的了解越多,难度就越大)

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

问题:目前我的内部循环只迭代一次(应该Monday迭代my_sub_dom=$( sed 's/=.*//' 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

完成回声“$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

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

谢谢

4

1 回答 1

0

给定一个weekly.txt包含

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

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

#!/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
于 2013-05-03T03:40:46.533 回答