7

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?

| improve this question | | | | |
  • 1
    Does list_members produce just the list of email addresses? One email address per line? – roaima Jul 23 '18 at 16:50
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
| improve this answer | | | | |
  • +1 for ts (look much easy than awk ..) – Archemar Jul 23 '18 at 16:57
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 '
| improve this answer | | | | |
3

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
| improve this answer | | | | |
0

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
| improve this answer | | | | |

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