Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load List From Text File To Bash Script

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"
like image 260
Simply_me Avatar asked Oct 21 '25 18:10

Simply_me


2 Answers

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
like image 183
Tanmoy Bandyopadhyay Avatar answered Oct 24 '25 11:10

Tanmoy Bandyopadhyay


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

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

like image 35
Dolphiniac Avatar answered Oct 24 '25 12:10

Dolphiniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!