Load List From Text File To Bash Script

牧云@^-^@ 提交于 2019-12-12 03:29:47

问题


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"

回答1:


Suppose, your datafile name is web.txt. Using command substitution (backtics) and cat, the array can be built. Pl. see the following code,

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



回答2:


Domain_list=()
while read addr
do
    Domain_list+=($addr)
done < addresses.txt

That should store each line of the text file into the array.




回答3:


I used the source command, and it works fine.

 #!/bin/bash

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


来源:https://stackoverflow.com/questions/16305143/load-list-from-text-file-to-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!