8

Suppose I run the command:

sudo ./list_members Physicians 

And I want to prefix the output like this:

Physicians [email protected]
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]

Is it possible for me to prefix StdOutput like that?

1
  • 1
    Does list_members produce just the list of email addresses? One email address per line? Commented Jul 23, 2018 at 16:50

4 Answers 4

9

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
0
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 '
2
  • Won't capture STDERR Commented May 19, 2020 at 3:57
  • @kos, see edit. Commented May 19, 2020 at 10:56
4

You can also do it with awk:

$ sudo ./list_members | awk '{print "Physicians "$0}'
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]

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 [email protected] xxx
Physician [email protected] yyy
Physician [email protected] zzz
Physician [email protected] aaa
0
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.