gpt4 book ai didi

bash - 在 bash 中执行 for-each

转载 作者:行者123 更新时间:2023-11-29 09:06:34 24 4
gpt4 key购买 nike

我正在寻找一个 Bash 单行程序,它为列表中的每个项目调用一次函数。例如,给定列表

foo bar baz
and the program "cowsay", it would produce:

 _____
< foo >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_____
< bar >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
_____
< baz >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||

(也许中间有额外的文字,并不重要)

我知道我可以用 bash 脚本做到这一点:

#!/bin/sh

for w in $@; do
cowsay $w
done

但我无法想象没有其他方法可以做到这一点。

编辑:我认为我最初的问题不是很清楚。我希望能够在不编写 bash 脚本的情况下做这样的事情:

locate foo | sed s/bar/baz/ | [other-processing] | [insert-magic-here] cowsay

关键是我试图避免必须编写脚本,这样我就可以将它添加到我的管道链中而不去考虑它。

最佳答案

你想要xargs。如果没有 forwhileuntil 循环结构,xargs 几乎是唯一可以执行您的操作的方法问。

如果您需要 xargs 为每个输入执行命令,而不是将许多输入作为单独的参数执行,请使用 -n1。您的示例变为:

$ locate foo | sed s/bar/baz/ | [other-processing] | xargs -n1 cowsay

关于bash - 在 bash 中执行 for-each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1697706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com