Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite a printed line in the shell with Ruby?

Tags:

shell

ruby

How would I overwrite the previously printed line in a Unix shell with Ruby?

Say I'd like to output the current time on a shell every second, but instead of stacking down each time string, I'd like to overwrite the previously displayed time.

like image 948
Steph Thirion Avatar asked Feb 10 '11 23:02

Steph Thirion


4 Answers

You can use the \r escape sequence at the end of the line (the next line will overwrite this line). Following your example:

require 'time'

loop do
  time = Time.now.to_s + "\r"
  print time
  $stdout.flush
  sleep 1
end
like image 164
cam Avatar answered Nov 20 '22 06:11

cam


Use the escape sequence \r at the end of the line - it is a carriage return without a line feed.

On most unix terminals this will do what you want: the next line will overwrite the previous line.

You may want to pad the end of your lines with spaces if they are shorter than the previous lines.

Note that this is not Ruby-specific. This trick works in any language!

like image 37
jsegal Avatar answered Nov 20 '22 06:11

jsegal


Here is an example I just wrote up that takes an Array and outputs whitespace if needed. You can uncomment the speed variable to control the speed at runtime. Also remove the other sleep 0.2 The last part in the array must be blank to output the entire array, still working on fixing it.

#@speed = ARGV[0]

strArray = [ "First String there are also things here to backspace", "Second Stringhereare other things too ahdafadsf", "Third String", "Forth String", "Fifth String", "Sixth String", " " ]


#array = [ "/", "-", "|", "|", "-", "\\", " "]

def makeNewLine(array)
    diff = nil
    print array[0], "\r"
    for i in (1..array.count - 1)
        #sleep @speed.to_f
        sleep 0.2
        if array[i].length < array[i - 1].length
             diff = array[i - 1].length - array[i].length
        end
        print array[i]
        diff.times { print " " } if !diff.nil?
        print "\r"
        $stdout.flush

    end
end

20.times { makeNewLine(strArray) }

#20.times { makeNewLine(array)}
like image 1
Saloaty Avatar answered Nov 20 '22 05:11

Saloaty


Following this answer for bash, I've made this method:

def overwrite(text, lines_back = 1)
  erase_lines = "\033[1A\033[0K" * lines_back
  system("echo \"\r#{erase_lines}#{text}\"")
end

which can be used like this:

def print_some_stuff
  print("Only\n")
  sleep(1)
  overwrite("one")
  sleep(1)
  overwrite("line")
  sleep(1)
  overwrite("multiple\nlines")
  sleep(1)
  overwrite("this\ntime", 2)
end
like image 1
Jacquen Avatar answered Nov 20 '22 06:11

Jacquen