von*_*hev 2 command-line parallelism
假设我有一个命令接受一个文件路径参数:
mycommand myfile.txt
Run Code Online (Sandbox Code Playgroud)
现在我想对多个文件并行执行此命令,更具体地说,文件匹配 pattern myfile*。
有没有简单的方法来实现这一目标?
使用 GNUxargs和支持进程替换的 shell
xargs -r -0 -P4 -n1 -a <(printf '%s\0' myfile*) mycommand
Run Code Online (Sandbox Code Playgroud)
最多可mycommand并行运行 4秒。
如果mycommand不使用其标准输入,您还可以执行以下操作:
printf '%s\0' myfile* | xargs -r -0 -P4 -n1 mycommand
Run Code Online (Sandbox Code Playgroud)
这也适用于xargs现代 BSD。
要递归搜索myfile*文件,请将printf命令替换为:
find . -name 'myfile*' -type f -print0
Run Code Online (Sandbox Code Playgroud)
(-type f仅适用于常规文件。对于 glob 等效文件,您需要zsh及其printf '%s\0' myfile*(.))。
使用循环:
for f in myfile*; do
mycommand "$f" &
done
wait
Run Code Online (Sandbox Code Playgroud)
或使用GNU 并行.