tags:

views:

131

answers:

3

I have the following code:

puts "amit"
puts "ravi"

It outputs:

amit
ravi

I would like to redirect amit to one file and ravi to a different file.

Suppose my file name is name.rb. When I am trying like

system("name.rb > #{@filename}")

both amit and ravi are redirected to @filename but I want redirection to a different file or first it will redirect to two files of same name but in one file output is amit and in other file of same output is ravi.

+1  A: 

Have a look at Ruby Input/Output and Ruby File Handling.

phimuemue
sir is it possible to redirect different parts of the output to be redirect to differnt file or to same like amit to some file and ravi to different
Amit singh tomar
I do not think that one can "split" the ouput of a program and redirect it to different files unfortunately.
phimuemue
but sir i want it badly...
Amit singh tomar
Ok, so here some keywords that might do it:- consider two ouput methods: `STDOUT` and `STDERR`- if you work with unix and/or can not modify the ruby program itself, the following tools might be helpful: sed, awk, grep.
phimuemue
+2  A: 

Instead of redirecting you can pass filenames as arguments and write from ruby to the files:

open(ARGV[0], 'w') do |f|
  f.puts "amit"
end

open(ARGV[1], 'w') do |f|
  f.puts "ravi"
end

Then:

system("name.rb 1.txt 2.txt")
Leventix
sorry leventix i did not get you cud u expain it more
Amit singh tomar
nd suppose and very big means its of many line then what to do??
Amit singh tomar
This solution is applicable if you can modify the file that writes the text. If this is the case you should modify that program to output each line to the file you want.If you explain what you want to achieve, maybe we can help you more.
Leventix
+1  A: 

You can change the destination of $stdout and $stderr:

stout = File.open(ARGV[0], 'w')
sterr = File.open(ARGV[1], 'w')

$stdout.reopen(stout)
$stderr.reopen(sterr)

puts "something"
$stderr.puts "something another"
Gabor Garami
sir cud u plzz explain it more i m really strugglimg...like if my o/p like thatsetp viddec2 video_max_width 720setp viddec2 video_display onsetp viddec2 video_max_width 720setp viddec2 video_display offhow to i redirect two parts of my o/p seprated my newlines to two differnt files plzzzsir help me or anyone else knows first part of o/p means setp viddec2 video_max_width 720setp viddec2 video_display on generated by one loop and second part by other loop and suppose my filename is main.rb and i m doing system("filee.rb > #{@filename}")
Amit singh tomar
i am able to redirect whole o/p to @filename but i want first part of o/p to be redirected to one file and other part o/p to some other file system("main.rb > #{@filename}") that i m doing
Amit singh tomar
nd how in my case i can change destination of $stdout
Amit singh tomar