reading lines from standard input or a two way pipe into an array

reading lines from standard input or a two way pipe into an array

am 26.11.2007 10:26:52 von hyperboogie

Hi

I'm trying to read the output of 'ls -lartF' into an array, a line
into each array element
I've tried to do this in 3 different ways

1. I've managed to do this is using a two way pipe, as follows:

#!/bin/ksh

i=0
ls -lartF |&
while read -p line; do
print - "$line"
aline[i]="$line"
let i=i+1
done

Is there a way of doing the this without being a smartass (i.e.
without two way pipes)

2. In the following way it's all read as a single line into the first
array element:

#!/bin/ksh

i=0
print -r $(ls -lartF) > tmpshiron
while read -r line; do
print -r "$line"
aline[i]="$line"
let i=i+1
done < tmpfile
rm tmpfile

how can I read the output as lines?
is there a way I can read the lines without using a tempfile ???

3. I've tried (and failed) "feeding" the loop from the subprocess, as
follows:

while read -r line; do
...
...
done < $(ls -lartF)

what is the most straight forward way of doing this?

Thanks
Shiron

Re: reading lines from standard input or a two way pipe into an array

am 26.11.2007 13:22:53 von Janis Papanagnou

On 26 Nov., 10:26, hyperboogie wrote:
> Hi
>
> I'm trying to read the output of 'ls -lartF' into an array, a line
> into each array element
> I've tried to do this in 3 different ways
>
> 1. I've managed to do this is using a two way pipe, as follows:
>
> #!/bin/ksh
>
> i=0
> ls -lartF |&
> while read -p line; do
> print - "$line"
> aline[i]="$line"
> let i=i+1
> done
>
> Is there a way of doing the this without being a smartass (i.e.
> without two way pipes)
>
> 2. In the following way it's all read as a single line into the first
> array element:
>
> #!/bin/ksh
>
> i=0
> print -r $(ls -lartF) > tmpshiron
> while read -r line; do
> print -r "$line"
> aline[i]="$line"
> let i=i+1
> done < tmpfile
> rm tmpfile
>
> how can I read the output as lines?
> is there a way I can read the lines without using a tempfile ???
>
> 3. I've tried (and failed) "feeding" the loop from the subprocess, as
> follows:
>
> while read -r line; do
> ..
> ..
> done < $(ls -lartF)
>
> what is the most straight forward way of doing this?

Simple pipes...

ls -lartF |
while read -r line; do
...
done

Or, if you want to work on separate fields within the loop, enumerate
the fields in the read list...

ls -lartF |
while read -r var1 var2 var3 rest_of_line
do
...
done


Janis

>
> Thanks
> Shiron

Re: reading lines from standard input or a two way pipe into an array

am 26.11.2007 14:12:24 von pgas

hyperboogie wrote:
> I'm trying to read the output of 'ls -lartF' into an array, a line
> into each array element


O=$IFS IFS=$'\n';array=( $(IFS=$O;ls -lartF) );IFS=$O;printf "%s\n" "${array[@]}"

--
pgas @ SDF Public Access UNIX System - http://sdf.lonestar.org