3

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"
Simply_me
  • 2,840
  • 4
  • 19
  • 27
  • 3
    Your question has been answered before: http://stackoverflow.com/questions/1688999/how-can-i-read-a-list-of-filenames-from-a-file-in-bash – Bill Apr 30 '13 at 16:59

4 Answers4

5

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

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"
Simply_me
  • 2,840
  • 4
  • 19
  • 27
1
Domain_list=()
while read addr
do
    Domain_list+=($addr)
done < addresses.txt

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

Dolphiniac
  • 1,632
  • 1
  • 9
  • 9
  • thank you for your answer, but a quick question, is there a difference (as how the script stores it) between the way I've implemented it and your way? – Simply_me Apr 30 '13 at 17:22
1

There's no need for a counter if we're sourcing the list from a file. You can simply iterate through the list and echo the value.

#!/bin/bash

source domain.txt
for i in ${domain_list[@]}
do
   echo $i
done