Unix Shell - How to read an array from a file?

This is Interesting: Free IT Magazines  
Home > Archive > Unix Shell > February 2006 > How to read an array from a file?





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author How to read an array from a file?
SQ

2006-02-21, 5:54 pm

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

Chris

2006-02-21, 5:54 pm

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

Chris

2006-02-21, 5:54 pm

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
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com