Issue in using read keyword twice

Hi,

I have a situation where i need to read line by line from a text pad and with each line , i need to take inputs from command line and do some process.
Using below code i am not able to use 'read' keyword twice.

Can any one please help

cat > t.txt
a
d
c
 
> cat > t.ksh
while read line
do
echo "press oprion"
read kind
echo "kind=$kind
echo "line=$line
done<t.txt

> sh t.ksh
press oprion
kind=d
echo line=a
press oprion
kind=
echo line=c

Ravindra,

Your script:

is working as written, once the missing quotes were added:

$ ksh -x t.ksh 
+ 0< t.txt
+ read line
+ echo 'press oprion'
press oprion
+ read kind
+ echo kind=d
kind=d
+ echo line=a
line=a
+ read line
+ echo 'press oprion'
press oprion
+ read kind
+ echo kind=
kind=
+ echo line=c
line=c
+ read line

The first read assigned "a" to line, the second read assigned "d" to kind. The loops repeats and assigned "c" to line and "" to kind. Maybe this would make more sense if the input file contained:

Line 1  a
Line 2  d
Line 3  c
Line 4   

And the resulting output would be:

press oprion
kind=Line 2  d
line=Line 1  a
press oprion
kind=Line 4
line=Line 3  c

Is this the desired behavior?

Hi derekludwig,

Thanks for reply,

My expectation is something else.

Alternate display of input from command editor and each line from text pad.
If 1,2,3 are the 3 inputs supplied, then
O/P:

kind=1
line=a
kind=2
line=d
kind=3
line=c

If I understand correctly, you want to read from the terminal every other time. You can do that with input redirection. Try:

exec 3<&0

while read line
        do      echo "press oprion"
                read kind <&3
                echo "kind=$kind"
                echo "line=$line"
        done < t.txt

This duplicates file descriptor 3 from stdin (terminal) fd 0. The second read uses this fd to get its input from. In the while block, stdin is redirected from your text file. Result:

press oprion
1
kind=1
line=a
press oprion
2
kind=2
line=d
press oprion
3
kind=3
line=c
1 Like

Or use the extra descriptor for the while-loop's input

while read line <&3
do echo "press oprion"
read kind
echo "kind=$kind"
echo "line=$line"
done 3< t.txt