| Author |
How to read an array from a file?
|
|
|
| This is in ksh. I want to read in a file and put it in the array.
Let's assume that the file contains one key per line:
key1
key2
key3
....
keyn
| |
|
| SQ wrote:
> This is in ksh. I want to read in a file and put it in the array.
> Let's assume that the file contains one key per line:
>
> key1
> key2
> key3
> ...
> keyn
This seems to work for me (ksh on AIX):
set -A key_list `cat foo` # where "foo" contains one key on each line
for i in ${key_list[@]}
do
echo $i
done
Chris
| |
|
| Sorry, I posted without previewing! I mean that "foo" is the name of a
_file_ I created that contains one key per line.
| |
| Stephane CHAZELAS 2006-02-21, 5:54 pm |
| 2006-02-21, 09:01(-08), SQ:
> This is in ksh. I want to read in a file and put it in the array.
> Let's assume that the file contains one key per line:
>
> key1
> key2
> key3
> ...
> keyn
If you want to have the array have an element per line of the
file, then it's:
set -A a
while IFS= read -r line; do
a[${a[#a[@]}]=$line
done < file
If you want to have the array to have an element per non-empty
(but possibly blank) line of the file, you can do:
set -f
IFS='
'
set -A a -- $(< file)
If you want only the non-blank lines:
set -f
IFS='
'
set -A a -- $(grep '[^[:blank:]]' file)
But beware that some ksh implementations have a rather low limit
on the number of elements of an array (4096 and sometimes 1024).
But why would you want to do such things in a shell script? And
why write ksh scripts?
--
Stéphane
|
|
|
|