xargs
是 Linux 中一个非常强大的命令,用于从标准输入构建并执行命令行。它通常与其他命令(如 find
、grep
等)结合使用,以处理大量数据或文件。xargs
的核心功能是将输入数据转换为命令行参数。
xargs [选项] [命令]
xargs
从标准输入(stdin)读取数据。选项 | 说明 |
---|---|
-n |
指定每次执行命令时使用的参数个数。 |
-I |
用输入项替换占位符(通常为 {} )。 |
-p |
交互式模式,执行前提示用户确认。 |
-t |
打印执行的命令。 |
-r |
如果输入为空,则不执行命令。 |
-d |
指定输入的分隔符(默认是空格和换行)。 |
-a |
从文件读取输入,而不是标准输入。 |
-L |
指定每次执行命令时使用的行数。 |
-s |
设置命令行的最大长度。 |
--max-proC++s |
并行执行命令,指定最大进程数。 |
将输入作为参数传递给 echo
命令:
echo "file1 file2 file3" | xargs echo
输出:
file1 file2 file3
find
使用查找当前目录下的 .txt
文件并删除:
find . -name "*.txt" | xargs rm
-n
)每次只传递 2 个参数给 echo
:
echo "1 2 3 4 5" | xargs -n 2 echo
输出:
1 2
3 4
5
-I
)将输入项替换为占位符 {}
:
echo "file1 file2 file3" | xargs -I {} cp {} /backup/
这会将 file1
、file2
、file3
分别复制到 /backup/
目录。
-p
)在执行命令前提示用户确认:
echo "file1 file2 file3" | xargs -p rm
输出:
rm file1 file2 file3 ?...y
输入 y
确认执行。
-t
)在执行命令前打印命令:
echo "file1 file2 file3" | xargs -t echo
输出:
echo "file1 file2 file3" | xargs echo
0
-r
)如果输入为空,则不执行命令:
echo "file1 file2 file3" | xargs echo
1
(无输出)
-d
)使用逗号作为分隔符:
echo "file1 file2 file3" | xargs echo
2
输出:
file1 file2 file3
-a
)从文件 input.txt
读取输入:
echo "file1 file2 file3" | xargs echo
4
--max-procs
)并行执行命令,最多同时运行 2 个进程:
echo "file1 file2 file3" | xargs echo
5
这会同时运行 2 个 sleep
进程。
find
和 xargs
处理文件名中的空格如果文件名中包含空格,可以使用 find
的 -print0
和 xargs
的 -0
选项:
echo "file1 file2 file3" | xargs echo
6
将当前目录下的 .txt
文件重命名为 .bak
:
echo "file1 file2 file3" | xargs echo
7
使用 xargs
和 gzip
并行压缩文件:
echo "file1 file2 file3" | xargs echo
8
xargs
默认会将所有输入数据作为参数传递给命令,如果数据量过大,可能会导致命令行过长。可以使用 -n
或 -L
选项限制参数个数。find -print0
和 xargs -0
。xargs
,避免命令注入风险。xargs
是一个非常灵活的工具,特别适合处理大量数据或文件。通过结合其他命令(如 find
、grep
等),可以实现复杂的批量操作。掌握 xargs
的常用选项和技巧,可以显著提高工作效率。