'How do I do unbuffered substitution in a perl oneliner?

I've got a bash script that wraps mvn (Apache Maven) to add colour to its output. A cut-down version of what it does is:

mvn "$@" | sed -e "s/^\[INFO\] \-.*/$bldblu&$rst/g"

where $bldblu is the ANSI color escape characters for bold blue, and $rst resets the colours.

The issue I'm having is that sometimes mvn writes a line that doesn't end in a newline, thus (as far as I can tell) sed keeps waiting for input and never prints the prompt (which makes it seem like Maven is hanging). I've tried adding -u to sed but that just forces sed to do line-by-line buffering instead of buffering more than one line - not helpful for me.

So far this is what I've come up with:

mvn "$@" | perl -pe "$| = 1; s/^(\[INFO\] \-.*)/$bldblu\$1$rst/g"

but I think the use of -p is not correct here. Any help?



Solution 1:[1]

A substitution may be overkill, especially when the replacement pattern has special characters in it. How about this?

export bldblu
export rst
mvn "$@" | perl -pe 'if(/^.INFO. -/){ $_=$ENV{bldblu}.$_.$ENV{rst} }'

or rather than reinventing the wheel

mvn "$@" | perl -MTerm::ANSIColor -pe 
    '$_=color("bold blue").$_.color("reset") if /^.INFO. -/'

Solution 2:[2]

(workaround) Use sed --unbuffered

I couldn't figure out the solution but thankfully this is good enough for my particular usage:

cat - | sed --unbuffered 's/.*?from//'

But I too would like to know the answer. Perl one line substitution is a key idiom in my toolbelt.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mob
Solution 2 Sridhar Sarnobat