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)?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With