Reid Thompson
3/5/2009 4:03:00 PM
On Fri, 2009-03-06 at 00:43 +0900, Robert Klemme wrote:
> On 05.03.2009 16:07, Mmcolli00 Mom wrote:
> > How do you add a new line after you have split a text file with
> > continuous values delimited with commas? Thanks in advance. MC
> >
> > For example:
> > textfile contains: value1,value2,value3..
> >
> > I want to output this file like this:
> > value1
> > value2
> > value3
> >
> > #Here is my code:
> >
> > File.open('temp.txt', 'r') do |temp|
> > arraym = [] #<--I am using array so that I can use array functions
> > .but I dont have to use array for this
>
> This creation of the empty Array is completely superfluous as you do
> nothing with this Array. You even do not need to declare the variable
> outside of the block since you use it inside only and do not retain
> values between iterations (lines).
>
> > temp.each_line do |line|
> > arraym= line.split(",",0)
> > b.puts ""
> > b.puts arraym # + "\n"
> > b.puts ""
> > end
> > end
>
> It can be as simple as
>
> File.foreach "temp.txt" do |line|
> puts "", line.split(/,/), ""
> end
>
> You can as well do
>
> File.foreach "temp.txt" do |line|
> printf "\n%s\n", line.gsub(/,/, "\n")
> end
>
> Kind regards
>
> robert
>
rthompso@raker /tmp $ echo "value1,value2,value3" >/tmp/file.txt
rthompso@raker /tmp $ echo "value1,value2,value3" >/tmp/file2.txt
rthompso@raker /tmp $ echo "value1,value2,value3" >/tmp/file1.txt
rthompso@raker /tmp $ cat file*txt
value1,value2,value3
value1,value2,value3
value1,value2,value3
rthompso@raker /tmp $ ruby -p -i -e 'gsub(/,/, "\n")' file*.txt
rthompso@raker /tmp $ cat file*txt
value1
value2
value3
value1
value2
value3
value1
value2
value3