从文本文件加载列表到 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16305143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:17:54  来源:igfitidea点击:

Load List From Text File To Bash Script

bashlisttext-files

提问by Simply_me

I've a .txtfile which contains

我有一个.txt文件,其中包含

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?

我有兴趣将它作为列表(即Domain_List=( "abc.com" "google.com" .... "yahoo.com"))加载到 bash 脚本中。有可能吗?

Additional information, once the list is obtained it is used in a forloop and ifstatements.

附加信息,一旦获得列表,它就会在for循环和if语句中使用。

 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.txtallows me to use Domain_listas a list in the bash script.

更新:我已将格式更改为 Domain_list=( "google.com .... "yahoo.com" ),并且 usingsource Doamin.txt允许我Domain_list在 bash 脚本中用作列表。

#!/bin/bash

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

回答by Tanmoy Bandyopadhyay

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

假设您的数据文件名为 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

回答by Simply_me

I used the source command, and it works fine.

我使用了 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"

回答by Dolphiniac

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

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

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

回答by masterccioli

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