Question

I have a file which has N number of lines. I need to read each line and store it in a variable. For example, Firstline in var1, Secondline in var2, etc.

I tried the below while loop,

count=1;
while read line  
do  
var$count=`echo $line`  
echo -e "$var`$count`"  
done< input.txt 

In the above code, I am hitting error in the last but one line above!.

How to Reference a variable with another referenced variable?

Here, I am just echoing but actually I want the values stored in the variables to do some arithmetic calculations(like calculating time average).

Was it helpful?

Solution 2

Use an array in bash or ksh:

array=( $(< input.txt) )

echo ${array[0]} # first element
echo ${array[1]} # second element

echo ${#array[*]} # length

See here.

OTHER TIPS

As Mark Setchell noted, arrays are the preferable solution. They are available in KSh too:

set -A lines
count=1
while read line; do
    lines[$count]=$line
    echo -e ${lines[$count]}
    count=$(( $count + 1 ))
done < input.txt

For more details, take a look at this simple introduction with examples, or this chapter from O'Reilly's "Learning the Korn Shell" book.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top