我正在寻找一个Bash单行程序,它为列表中的每个项目调用一次函数.例如,给出列表
foo bar baz和程序"cowsay",它会产生:
_____
< foo >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_____
< bar >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_____
< baz >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Run Code Online (Sandbox Code Playgroud)
(也许中间有其他文字,并不重要)
我知道我可以使用bash脚本执行此操作:
#!/bin/sh
for w in $@; do
cowsay $w
done
Run Code Online (Sandbox Code Playgroud)
但我无法想象没有其他办法可以做到这一点.
编辑:我认为我在最初的问题上并不是很清楚.我希望能够在不编写bash脚本的情况下执行此类操作:
locate foo | sed s/bar/baz/ | [other-processing] | [insert-magic-here] cowsay
Run Code Online (Sandbox Code Playgroud)
关键是我试图避免编写脚本,以便我可以将它添加到我的管道链而不考虑它.
Nic*_*ley 11
听起来你想要使用xargs.
$ echo foo bar | xargs -n 1 cowsay
_____
< foo >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_____
< bar >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Run Code Online (Sandbox Code Playgroud)
你想要的xargs.如果没有for,while或until循环结构,xargs是关于将做什么你问的嘛.
-n1如果需要xargs为每个输入执行命令,请使用,而不是使用许多输入作为单独的参数执行.你的例子变成:
$ locate foo | sed s/bar/baz/ | [other-processing] | xargs -n1 cowsay
Run Code Online (Sandbox Code Playgroud)
在一行中:
for i in foo bar baz; do cowsay $i; done
Run Code Online (Sandbox Code Playgroud)
或者更清楚:
foobar="foo bar baz"
for i in $foobar
do
cowsay $i
done
Run Code Online (Sandbox Code Playgroud)