Looking for something like this? Any ideas?

cmd | prepend "[ERRORS] "

[ERROR] line1 text
[ERROR] line2 text
[ERROR] line3 text
... etc
link|improve this question
feedback

5 Answers

up vote 8 down vote accepted
cmd | while read line; do echo "[ERROR] $line"; done

has the advantage of only using bash builtins so fewer processes will be created/destroyed so it should be a touch faster than awk or sed.

link|improve this answer
1  
This actually only reduces the process count by one. (But it might be faster because no regexps (sed) or even string splitting (awk) are used.) – grawity Oct 9 '09 at 7:52
BTW, I was curious about performance and here are results of my simple benchmark using bash, sed and awk. Pushing about 1000 lines of text (dmesg output) to FIFO file and then reading them like this: pastebin.ca/1606844 Looks like awk is the winner. Any ideas why? – Ilya Zakreuski Oct 9 '09 at 11:12
1  
be careful running timing tests like that - try running them in all 6 different orders and then averaging the results. Different orders to mitigate block cache effects and average to mitigate background interruption/scheduling effects. – pjz Oct 9 '09 at 18:25
feedback

Try this:

cmd | awk '{print "[ERROR] " $0}'

Cheers

link|improve this answer
feedback
cmd | sed 's/.*/[ERROR] &/'
link|improve this answer
2  
sed 's/^/[ERROR] /' – grawity Oct 9 '09 at 7:49
feedback

I wanted a solution that handled stdout and stderr, so I wrote prepend.sh and put it in my path:

#!/bin/bash

prepend_lines(){
  local prepended=$1
  while read line; do
    echo "$prepended" "$line"
  done
}

tag=$1

shift

"$@" > >(prepend_lines "$tag") 2> >(prepend_lines "$tag" 1>&2)

Now I can just run prepend.sh "[ERROR]" cmd ..., to prepend "[ERROR]" to the output of cmd, and still have stderr and stdout separate.

link|improve this answer
feedback

With all due credit to @grawity, I'm submitting his comment as an answer, as it seems the best answer here to me.

sed 's/^/[ERROR] /' cmd
link|improve this answer
Why is this preferable to the bash solution? – user14645 Jan 31 at 18:04
I suppose it depends on your purpose. If your goal is to simply prepend to every line in a file, this accomplishes that goal with very few characters, using a very familiar tool. I far prefer that to a 10 line bash script. The awk one-liner is nice enough, but I think that more people are familiar with sed than awk. The bash script is good for what it does, but it seems that it is answering a question that was not asked. – Eric Wilson Jan 31 at 18:22
The answer that pjz submitted is also a nice one-liner. It doesn't additional programs, processes and may run a little quicker. – user14645 Feb 2 at 18:11
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.