8

Suppose I run the command:

sudo ./list_members Physicians 

And I want to prefix the output like this:

Physicians user@domain.com
Physicians user2@domain.com
Physicians user3@domain.com
Physicians user4@domain.com

Is it possible for me to prefix StdOutput like that?

Ran Dom
  • 181

4 Answers4

10

I'd suggest you using ts utility from moreutils package. Though its primary purpose is prepending output lines with a time stamp, it can use an arbitrary string along or instead of the timestamp

for line in {01..05}; do echo $line; done | ts  "A string in front "
A string in front  01
A string in front  02
A string in front  03
A string in front  04
A string in front  05
Archemar
  • 31,554
Tagwint
  • 2,480
8

Use the stream editor:

sudo ./list_members Physicians | sed 's/^/Physicians /'

To make it a helper function, you may prefer awk though:

prefix() { P="$*" awk '{print ENVIRON["P"] $0}'; }

sudo ./list_members Physicians | prefix 'Physicians '

If you wanted to prefix both stdout and stderr, that could be done with:

{
  sudo ./list_members Physicians 2>&1 >&3 3>&- |
   prefix 'Physicians ' >&2 3>&-
} 3>&1 | prefix 'Physicians '
4

You can also do it with awk:

$ sudo ./list_members | awk '{print "Physicians "$0}'
Physicians user@domain.com
Physicians user2@domain.com
Physicians user3@domain.com
Physicians user4@domain.com

Or with xargs:

$ sudo ./list_members | xargs -n1  echo 'Physician'

If you know your ./list_members will be including more than 1 argument you can use this xargs which splits the input being fed to it on \n instead:

$ sudo ./list_members | xargs -n1 -d $'\n' echo 'Physician'
Physician user@domain.com xxx
Physician user2@domain.com yyy
Physician user3@domain.com zzz
Physician user4@domain.com aaa
slm
  • 369,824
1

Using the Bourne shell (or BASH, which is a superset) to do it will keep the solution 100% POSIX:

sudo ./list_members | while read LINE; do echo "Prefix ${LINE}"; done
Blrfl
  • 384