cat a.txt | xargs -I % echo %
在上面的例子中,xargs使用echo %作为命令参数。但在某些情况下,我需要多个命令来处理参数,而不是一个。例如:
cat a.txt | xargs -I % {command1; command2; ... }
但是xargs不接受这种形式。我知道的一种解决方案是,我可以定义一个函数来包装命令,但我想避免这样做,因为它很复杂。有没有更好的解决方案?
cat a.txt | xargs -I % echo %
在上面的例子中,xargs使用echo %作为命令参数。但在某些情况下,我需要多个命令来处理参数,而不是一个。例如:
cat a.txt | xargs -I % {command1; command2; ... }
但是xargs不接受这种形式。我知道的一种解决方案是,我可以定义一个函数来包装命令,但我想避免这样做,因为它很复杂。有没有更好的解决方案?
当前回答
我更喜欢允许试运行模式的样式(没有| sh):
cat a.txt | xargs -I % echo "command1; command2; ... " | sh
管道也适用:
cat a.txt | xargs -I % echo "echo % | cat " | sh
其他回答
我有一个解决这个问题的好办法。 只要写一个命令mcmd,就可以了
find . -type f | xargs -i mcmd echo {} @@ cat {} @pipe sed -n '1,3p'
mcmd的内容如下:
echo $* | sed -e 's/@@/\n/g' -e 's/@pipe/|/g' | csh
我做的一件事是添加到.bashrc/。配置此功能:
function each() {
while read line; do
for f in "$@"; do
$f $line
done
done
}
然后你就可以做
... | each command1 command2 "command3 has spaces"
它比xargs或-exec更简洁。如果还需要这种行为,还可以修改该函数,将读取的值插入到每个命令中的任意位置。
这是另一种没有xargs和cat的方法:
while read stuff; do
command1 "$stuff"
command2 "$stuff"
...
done < a.txt
试试这个:
git config --global alias.all '!f() { find . -d -name ".git" | sed s/\\/\.git//g | xargs -P10 -I{} git --git-dir={}/.git --work-tree={} $1; }; f'
它并行运行10个线程,并执行任何你想要在文件夹结构中全部回购的git命令。无论回购是1层还是n层。
例句:get all pull
对我来说另一个可行的解决方案是——
cat a.txt | xargs bash -c 'command1 $@; command2 $@' bash
注意结尾的“bash”-我假设它作为argv[0]传递给bash。在这种语法中,如果没有它,每个命令的第一个参数将丢失。它可能是任何一个词。
例子:
cat a.txt | xargs -n 5 bash -c 'echo -n `date +%Y%m%d-%H%M%S:` ; echo " data: " $@; echo "data again: " $@' bash