假设我运行命令:
sudo ./list_members Physicians
我想给输出添加前缀,如下所示:
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]
我可以像这样给 StdOutput 添加前缀吗?
答案1
我建议您使用ts
moreutils 包中的实用程序。尽管其主要目的是在输出行前面添加时间戳,但它可以使用任意字符串或代替时间戳
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
答案2
使用s特雷姆编辑伊托:
sudo ./list_members Physicians | sed 's/^/Physicians /'
为了使其成为辅助函数,您可能awk
更喜欢:
prefix() { P="$*" awk '{print ENVIRON["P"] $0}'; }
sudo ./list_members Physicians | prefix 'Physicians '
如果您想为 stdout 和 stderr 添加前缀,可以通过以下方式完成:
{
sudo ./list_members Physicians 2>&1 >&3 3>&- |
prefix 'Physicians ' >&2 3>&-
} 3>&1 | prefix 'Physicians '
答案3
您还可以使用以下方法进行操作awk
:
$ sudo ./list_members | awk '{print "Physicians "$0}'
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]
Physicians [email protected]
或者与xargs
:
$ sudo ./list_members | xargs -n1 echo 'Physician'
如果您知道您./list_members
将包含超过 1 个参数,您可以使用它xargs
来分割输入的输入\n
:
$ 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
答案4
使用 Bourne shell(或 BASH,它是一个超集)来执行此操作将使解决方案保持 100% POSIX:
sudo ./list_members | while read LINE; do echo "Prefix ${LINE}"; done