2

I've a .txt file which contains

abc.com
google.com
....
....
yahoo.com

And I'm interested in loading it to a bash script as a list (i.e. Domain_List=( "abc.com" "google.com" .... "yahoo.com") ). Is it possible to do?

Additional information, once the list is obtained it is used in a for loop and if statements.

 for i in "${Domain_list[@]}
 do
     if grep -q "${Domain_list[counter]}" domains.log
   ....
   ....
     fi
 ....
     let counter=counter+1
 done

Thank you,

Update: I've changed the format to Domain_list=( "google.com .... "yahoo.com" ), and using source Doamin.txt allows me to use Domain_list as a list in the bash script.

#!/bin/bash

counter=0
source domain.txt
for i in "${domain_list[@]}"
do
   echo "${domain_list[counter]}"
   let counter=counter+1
done
echo "$counter"
4

4 回答 4

3

假设您的数据文件名为 web.txt。使用命令替换(backtics)和 cat,可以构建数组。PL。看下面的代码,

myarray=(`cat web.txt`)
noofelements=${#myarray[*]}
#now traverse the array
counter=0
while [ $counter -lt $noofelements ]
do
    echo " Element $counter is  ${myarray[$counter]}"
    counter=$(( $counter + 1 ))

done
于 2013-04-30T17:18:10.173 回答
1

我使用了 source 命令,它工作正常。

 #!/bin/bash

 counter=0
 source domain.txt
 for i in "${domain_list[@]}"
 do
    echo "${domain_list[counter]}"
    let counter=counter+1
 done
 echo "$counter"
于 2013-04-30T17:20:50.173 回答
1
Domain_list=()
while read addr
do
    Domain_list+=($addr)
done < addresses.txt

那应该将文本文件的每一行存储到数组中。

于 2013-04-30T17:01:55.267 回答
0

如果我们从文件中获取列表,则不需要计数器。您可以简单地遍历列表并回显该值。

#!/bin/bash

source domain.txt
for i in ${domain_list[@]}
do
   echo $i
done
于 2020-04-12T17:02:32.450 回答