Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse progress with sed (or something else)

Tags:

bash

parsing

sed

I am trying to parse progress from one program (it is mkvmerge, but I hope that does not matter):

 echo -en "Progres: 0%" ; sleep 1 ; echo -en "\b\b25%" ; sleep 1 ; echo -en "\b\b\b50%" ; sleep 1 ; echo -en "\b\b\b75%" ; sleep 1 ; echo -e "\b\b\b100%" 

I would like to get the number without "Progress " and "%". This works:

echo -e "Progress: 0%"| sed -e 's/Progress: //' -e 's/%//' -e 's/\(....\)\(..\)\(..\)/\1-\2-\3/'

But when the Progress keeps changing, it does not work. Is there a way to do it (even without sed and with something else)?

like image 537
sup Avatar asked Jun 19 '26 01:06

sup


2 Answers

The \b characters are changing the current line so a new line never gets printed. You're not going to have a great deal of success out of the box using a line-based stream editor like sed on that kind of input.

If mkvmerge is generating this kind of output first try looking for a switch that makes it use some other kind of progress indicator (preferrably one that prints newlines).

If that doesn't work you can try replacing the backspaces with newlines:

( echo -en "Progres: 0%" ; sleep 1 ; echo -en "\b\b25%" ; sleep 1 ; echo -en "\b\b\b50%" ; sleep 1 ; 
  echo -en "\b\b\b75%" ; sleep 1 ; echo -e "\b\b\b100%" ) | tr '\b' '\n'

Add some unbuffering using stdbuf and it seems we're there, at least for your example:

( echo -en "0%" ; sleep 1 ; echo -en "\b\b25%" ; sleep 1 ; echo -en "\b\b\b50%" ; sleep 1 ; 
  echo -en "\b\b\b75%" ; sleep 1 ; echo -e "\b\b\b100%" ) | stdbuf -i0 -o0 -e0 tr '\b' '\n' | 
  stdbuf -i0 -o0 -e0 sed -e 's/Progress: //' -e 's/%//' -e 's/\(....\)\(..\)\(..\)/\1-\2-\3/'

The output, which appeared in the screen as it was generated thanks to stdbuf (I trimmed some spurious newlines):

0
25
50
75
100
like image 200
Eduardo Ivanec Avatar answered Jun 20 '26 21:06

Eduardo Ivanec


Try piping through tr to turn carriage returns (most likely what it's using) into line feeds:

<cmd> | tr '\r' '\n' | sed ...

Then you can work with it separated into lines like you normally would.

like image 39
FatalError Avatar answered Jun 20 '26 23:06

FatalError



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!