Operating System - HP-UX
1751865 Members
5782 Online
108782 Solutions
New Discussion юеВ

sh-posix script reading an array from a file with spaces in each element.

 
SOLVED
Go to solution
Stephen McKay_3
Occasional Advisor

sh-posix script reading an array from a file with spaces in each element.

I am writing a script where I want to read the contents of a text file into an array.

Presently, I have code that looks like this:
GRAPH7[0]="CPU Summary"
GRAPH7[1]="Individual CPUs"
GRAPH7[2]="Disk Space"

Instead I want to read this array from a text file, so it can be maintained without editing the script. The text file looks like this:

CPU Summary
Individual CPUs
Disk Space

If I try this:
set -A GRAPH7 $( <7_day_graphs.ini )

I get each word assigned to a variable, instead of each line.

If I try this:
set -A GRAPH7 "$( <7_day_graphs.ini )"

I get only one variable in my array, with all the lines in it.

I can't figure out how to read one line at a time since each line contains spaces.

Any ideas?
4 REPLIES 4
Denver Osborn
Honored Contributor

Re: sh-posix script reading an array from a file with spaces in each element.

try somthing like this...


COUNT=0

while read line
do
GRAPH7[$COUNT]="$line"
((COUNT=$COUNT + 1))
done < 7_day_graphs.ini


Hope this helps,
-denver
Muthukumar_5
Honored Contributor

Re: sh-posix script reading an array from a file with spaces in each element.

You can directly do the operation from file itself as,

while read line; do

operation $line

done < filename

If you want to assign into variable then,

index=0
read -r line; do

set GRAPH[$index]=$line
let index=index+1

done <

hth.
Easy to suggest when don't know about the problem!
Ermin Borovac
Honored Contributor
Solution

Re: sh-posix script reading an array from a file with spaces in each element.

Simply set IFS to newline character before set -A.

OLD_IFS=$IFS
IFS='
'
set -A arr $(IFS=$OLD_IFS
Stephen McKay_3
Occasional Advisor

Re: sh-posix script reading an array from a file with spaces in each element.

reseting IFS top only a newline (printf "\n") worked like a charm.

Thanks for the ideas!