ruby hidden characters 25l 25h from file

124 Views Asked by At

A file which contains line as below,

[root@test-server ~]# cat /tmp/output.log


Done

[root@test-server ~]#

But it has some hidden characters,

[root@test-server ~]# cat -e /tmp/output.log
^[[?25l$
$
^[[?12l^[[?25hDone!$
$
[root@test-server ~]# 

here are the bytes code of these characters,

[root@test-server ~]# irb
irb(main):001:0> File.open("/tmp/output.log").each_byte.to_a
=> [27, 91, 63, 50, 53, 108, 10, 10, 27, 91, 63, 49, 50, 108, 27, 91, 63, 50, 53, 104, 68, 111, 110, 101, 10, 10]
irb(main):002:0>

Am trying to remove this using below gsub method which is not working.

filename="/tmp/stop_output.log"
content = File.read(filename)
content.gsub!(/\e\[?(\d+)(;(\d+))?l|\e\[?(\d+)(;(\d+))?h/, '')

Not sure if am missing something with gsub,

1

There are 1 best solutions below

2
On

Got it fixed myself. I found that not escaping ?.

irb(main):021:0> filename="/tmp/output.log"
=> "/tmp/output.log"
irb(main):022:0> content = File.read(filename)
=> "\e[?25l\n\n\e[?12l\e[?25hDone\n\n"
irb(main):023:0> content.gsub!(/\e\[\?(\d+)(\d+)l|\e\[\?(\d+)(\d+)h/, '')
=> "\n\nDone\n\n"
irb(main):024:0> puts content


Done

=> nil
irb(main):025:0>

Thanks!