Reading a variable line by line with while loop

Ray Parrish crp at cmc.net
Tue Dec 1 14:23:10 UTC 2009


Loïc Grenié wrote:
> 2009/12/1 Ray Parrish <crp at cmc.net>:
>   
>> Hello,
>>
>> I have been using while loops to read files in line by line when I want
>> to process things on a line oriented basis. Sometimes i have the set of
>> lines I want to read through already in a variable, and have to write
>> them to file before beginning to read line by line.
>>
>> I was wondering if it is possible to read a variable line by line
>> somehow with a while loop? Would it possibly be faster than using a file
>> to read from?
>>
>> I was thinking something along the lines of the following code might
>> work, but have not tested it yet.
>>
>> while read ThisLine; do
>>      # process each line
>>      echo "$ThisLine"
>> done < `echo "$Variable"`
>>
>> Is this something that might work, and would it be more efficient than
>> writing to, and reading from a file? Is there some other way I've missed
>> to make it work?
>>     
>
>     This will probably not work.
>
> echo "$Variable" | while read
> ...
> done
>
>     has better chances of working.
>
>            Loïc
>   
Well, that one test worked, but I cannot get the following to work -

# Read bash history into a variable for use with combobox call
History=""
BashHistory=`cat ~/.bash_history`
echo "$BashHistory" | while read ThisCommand; do
     # Replace spaces in each command line with __ [double underlines]
     ThisCommand=${ThisCommand// /__}
     # Concatenate the results to the Command variable
     History="$History $ThisCommand"
done
echo "History - $History"

The last echo command returns nothing, but if I put an echo command in 
the loop either before, or after the replace spaces command, it echoes 
every line of the variable to the console.

Does anyone have any idea why it's not working because I am stumped...

Later, Ray Parrish

-- 
The Future of Technology.
http://www.rayslinks.com/The%20Future%20of%20Technology.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com






More information about the ubuntu-users mailing list