Shell script to read a file and store in variables

I have a input file like this.

Sample.txt

30    | TXDatacenter | TXBackupDC
10    | UKDatacenter | UKBackupDC
0      | NLDatacenter | NLBackupDC
......
......
......

I need to get these values in different variables like this.

Load1=30
PriCenter1=TXDatacenter
BkpCenter1=TXBackupDC

Load2=10
PriCenter2=UKDatacenter
BklCenter2=UKBackupDC
....
...

Basically, I am looking to separate the contents of the file based on words. But i want to store the values in to variables based on its line number. (i.e Load1, 2,3 & its corresponding PriCenter1,2,3)

Any help is appreciated.

Thanks,
Visha

Try something like (bash):

i=1
while read Load x PriCenter x BkpCenter
do 
  (( i++ ))
done < file
$ echo "${PriCenter[2]}"
UKDatacenter

The variable $x is used as a dummy variable..

The following does what you want (assuming that your request to store the 3rd value in the 2nd line in BklCenter2 was a typo and you meant BkpCenter2 ) and shows that it worked. But I generally find that setting variables like this in a shell script isn't really what you want to do. It is usually much better to process a line at a time. If that can't be done for some reason, arrays are usually much easier to handle than variable names that have to be constructed on the fly (unless your script knows that there will always be the same number of input lines and that you want to process the values found on each line in a different way).

eval $(awk -F' *[|] *' '
{       printf("Load%d=\"%s\"\nPriCenter%d=\"%s\"\nBkpCenter%d=\"%s\"\n",
                NR, $1, NR, $2, NR, $3)
}' Sample.txt)
set|grep '^Load'
set|grep '^PriCenter'
set|grep '^BkpCenter'

If you want to try this on a Solaris/SunOS system, use /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk instead of awk .

Thanks. I prefer to use arrays. Can you guide me on that.

Thanks,
Visha

Using awk arrays:

awk -F"|" '{Load[NR]=$1;PriCenter[NR]=$2;BkpCenter[NR]=$3} END{for(i in Load) {print Load, PriCenter, BkpCenter}}' inputfile

Scrutinizer has already shown you how to use shell array variables (as long as you're using a shell that supports array variables (e.g., bash and ksh).

And, krishmaths has already shown you how to set up awk arrays (although the sample code given for this will include spaces in the variables that don't seem to be wanted).

Without knowing what you intend to do with this data (other than store it in an array), we have no way to know whether either of these suggestions will do what you need. So, what are you really trying to do?