0

This is my code. I want to grab the p's value and insert it into the file changed.txt when matched 1. But it doesn't do what I want to, it seems it doesn't know what #{p} is

Net::SSH.start( "192.168.2.1", "root", :password => "password") do |ssh|
    p = ssh.exec! "java -cp /var/lib/sonar/dev-tools.jar au.com.Tool test"
#   puts #{p}
    ssh.exec! "sed 's/1/#{p}/g' changed.txt"
end
lurker
  • 56,987
  • 9
  • 69
  • 103
gugo
  • 237
  • 2
  • 7
  • 17
  • Can you share what it actually does? Your `puts` debug statement should be `puts "#{p}"`. What are you getting for `#{p}` inside the `sed` regex? I ran a test case similar to this and it worked fine. – lurker Aug 23 '13 at 01:29
  • I would like replace 1 as p's value ; changed.txt only contains 1 inside. But with the current code, changed.txt still has 1, nothing is changed at all.. – gugo Aug 23 '13 at 01:32

1 Answers1

2

The passing of the p value the way you have it should work fine. However, the sed command doesn't change the file. If you want it to change the file in place, use the -i option like so:

ssh.exec! "sed -i 's/1/#{p}/g' changed.txt"

Or if you want the changes in a different file, then use:

ssh.exec! "sed 's/1/#{p}/g' changed.txt > newfile.txt"

An alternative option would be:

ssh.exec! "sed -i 's/1/" + p + "/g' changed.txt"
lurker
  • 56,987
  • 9
  • 69
  • 103
  • I thought 's/1/#{p}/g' #{p} should work too, however, when it's passed into sed, it's got nil value, as changed.txt is still same, not changed. Also thanks for correcting me the debug puts "#{p}". – gugo Aug 23 '13 at 02:36
  • @gugo, does your `puts` for `p` give you a non-nil output? What is the value of `p` in this case? – lurker Aug 23 '13 at 02:38
  • puts "#{p}" actually does output the value 619A72E67F796BD2. dev-tools.jar is a tool that generates encrypted text (in this case is test as written above), that I want it to replace the old text in the changed.txt. – gugo Aug 23 '13 at 03:06
  • hi mbratch, I found if I run this p=2 ssh.exec! "sed -i 's/1/#{p}/' chaged.txt", works. But not the one p = ssh.exec! "java ....", do you have an idea why? – gugo Aug 23 '13 at 05:21
  • @gugo, it appears that the function is doing the right thing as far as `sed` and `#{p}` is concerned. But the value of `p` returned by your `java` exec isn't what you expect. If it's returning `619A72E67F796BD2`, then of course it's not finding that in your text file. You'll need to investigate the execution of the `java...` command. – lurker Aug 23 '13 at 11:04