Search code examples
perlnewlinetail

How to override the last line with tail?


To monitor a log file I use the following command: tail -f -n 1 myfile.log | perl -ne 'print if s/progress (\d+).*/$1%/g' This will create lines with a a number in my terminal. How can I modify this command to overwrite the last line? Adding \r\033[K doesn't do the trick: tail -f -n 1 myfile.log | perl -ne 'print if s/progress (\d+).*/`\r\033[K$1%/g'


Solution

  • When you read a line in Perl, the trailing new-line character is not stripped. Also, a . in a regex does not match the new-line character unless the s modifier is present. Thus, in your second snippet, the \r character is always printed as the first character in a line and hence does not have any effect.

    To fix it, the following can be done:

    1. Add the s modifier in the regex to remove the new-line character as well.
    2. Before printing the string, print a \r character to move to the first position in the line.
    3. Since STDOUT is line-buffered, you need to change it to auto-flush every time something is printed. This can be done by assigning 1 to $|.

    Final code:

    perl -ne '$|=1; print if s/progress (\d+).*/\r$1%/s'