Here is my view. I think he is doing something similar to John, but seems to have a few smaller lines. I just included it here as an alternative, as I had a similar problem and wanted to try to define a more compact solution.
I think the main culprit for this problem is that the pipe | does not allow you to specify a stream similar to how it is redirected, for example. 2> .
The solution I came up with is to combine the output of a number of subshells with the internal processing of stdout , and then redirect it to an alternate temporary stream 3 .
The next subshell redirects stderr to stdin again and repeats the activity of the inner shell (although the prefix is with "E:" , not "O:" ). It redirects the output here to stdout again, although >&2 can be removed if you want to have everything in stdin (but I think keeping these streams separately is an advantage).
The outer shell joins the &3 thread again with stdin .
Since the two inner shells handle stdin and stdout separately (due to the alternative prefixes "O:" and "E:"), you need to run the perl command twice, so I wrapped it up in the fold function to maintain the order of things, and various things are also added here prefixes.
Perhaps you could end sed and include this in the perl regular expression, and also know that \\n is entered at the end of each line with your perl command. In fact, my personal opinion is that the linear folding introduced by this command should no longer be necessary, but I kept it for fidelity with your original problem.
function fold { perl -pe 's,\n,\\n,'g | sed 's/^\(.*\)$/'${1}':\1\n/' } while read line ; do echo "C:$line" ( ( ${line} | fold O >&3 ) 2>&1 | fold E >&2 ) 3>&1 done
source share