Array Values from Text or CSV File in Shell

Deadly 提交于 2020-01-16 08:03:31

问题


I am having a script in which I am declaring arrays like below:

declare -a Pool=("Terrace|HouseTerrace_")
declare -a Library=("lib1 lib2 lib3")
declare -a Name=("Guru/Raju Albert Deepak")
declare -a Email=("Guru@american.com,Raju@american.com Albert@american.com Deepak@amaerican.com")
Sub=("Media Rotation")
i=0
while [ $i -lt ${#Pool[@]}  ]
do
command blah balh blah
i=`expr $i + 1`
done

Now what i want is that instead of declaring values in aaray here i should import it from file (either text or csv ) or is there any better way perfroming this task. I don want to give access to script file to users.


回答1:


This is a partial answer, to help kick-start the OP effort.

The bash "readarray" can be used to load an array from a file. For example they code declare -a email=("a@a.com" "b@b.com" ...) can be replaced with

readarray email < email.txt

Where email.txt is (using posted data)

Guru@american.com
Raju@american.com
Albert@american.com
...

Another suggest improvement will be to use for item in instead of while loops to iterate over arrays. Instead of i=0 ; while [ $i -lt ${#Pool[@]} ] ; do ... ; done

for p in "${pool[@]}" ; do
   command $p
done


来源:https://stackoverflow.com/questions/59098794/array-values-from-text-or-csv-file-in-shell

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