0

am in a need of using an array to set the variable value for further manipulations from the output file.

scenario:

> 1. fetch the list from database 
> 2. trim the column using sed to a file named x.txt (got specific value as that is required)
> 3. this file x.txt has the below output as
10000 
20000 
30000
> 4. I need to set a variable and assign the above values to it.  
A=10000 
B=20000 
C=30000
> 5. I can invoke this variable A,B,C for further manipulations.

Please let me know how to define an array assigning to its variable from the output file.

Thanks.

Velu
  • 23
  • 4
  • Do you want to write a shell script? For which shell? See https://stackoverflow.com/a/30988704/10622916 – Bodo Feb 06 '19 at 17:25
  • It looks like you want 3 variables named A, B, and C. Where is the array? – William Pursell Feb 06 '19 at 17:28
  • To be specific the x.txt file contains below values 10.20.30.40 20.30.40.50 I want the above output to be assigned to a variable say SET[i] SET1=10.20.30.40 SET2=20.30.40.50 So I can invoke SET1 and SET2 for further manipulations. – Velu Feb 06 '19 at 17:40
  • @Bodo - thanks for the link it works using mapfile -t. – Velu Feb 06 '19 at 18:03
  • I can copy this to an answer to make the question more useful for others. I suggest to add a `bash` tag. – Bodo Feb 06 '19 at 18:10
  • added bash tag. – Velu Feb 06 '19 at 18:16
  • mapfile -t arr < file.txt for((i=0;i<3;I++)) do echo "SET$i=${arr[$i]}" done this worked. thanks. – Velu Feb 06 '19 at 18:19

2 Answers2

0

I am not a big proponent of using arrays in bash (if your code is complex enough to need an array, it's complex enough to need a more robust language), but you can do:

$ unset a
$ unset i
$ declare -a a
$ while read line; do a[$((i++))]="$line"; done < x.txt

(I've left the interactive prompt in place. Remove the leading $ if you want to put this in a script.)

William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

In bash (starting from version 4.x) and you can use the mapfile command:

mapfile -t myArray < file.txt

see https://stackoverflow.com/a/30988704/10622916

or another answer for older bash versions: https://stackoverflow.com/a/46225812/10622916

Bodo
  • 9,287
  • 1
  • 13
  • 29