18448

92 分钟

#Bash 的 xargs 命令

xargs [OPTION]... [CMD [ARG]...]

功能

从标准输入构建命令行并执行。

类型

可执行文件(/usr/bin/xargs),属于 findutils

参数

  • OPTIONS 选项:
    • -0, --null - 输入项以空字符(\0)作为分隔符(而非默认的空格或换行符),引号和反斜杠不再特殊处理
    • -a file, --arg-file=file - 从文件而非标准输入读取数据
    • --delimiter=delim, -d delim - 输入项以 delim 作为分隔符
    • -E eof-str - 以 eof-str 作为文件结束符
    • -e[eof-str], --eof[=eof-str] - 同 -E;不建议使用此选项
    • -I replace-str - 将 ARG 中出现的 replace-str 替换为从标准输入读取的字符串;使用此选项每行 1 行执行一次命令
    • -i[replace-str], --replace[=replace-str] - -I;已弃用
    • -L max-lines - 每 max-lines 行输入执行一行命令
    • -l[max-lines], --max-lines[=max-lines] - -L;已弃用
    • -n max-args, --max-args=max-args - 每条命令行最多可以使用 max-args 个参数
    • -P max-procs, --max-procs=max-procs - 一次可最多运行 max-procs 个进程;默认为 1
    • -o, --open-tty - 在执行命令之前,先在子进程中将 stdin 重新打开为 /dev/tty
    • -p, --interactive - 交互式执行;运行每条命令前先进行询问
    • --process-slot-var=name - 在每个运行的子进程中,将环境变量 name 设置为进程的唯一编号
    • -r, --no-run-if-empty - 如果标准输入不包含任何非空白字符,则不执行该命令
    • -s max-chars, --max-chars=max-chars - 每条命令行最多使用 max-chars 个字符,包括命令、初始参数以及参数字符串末尾的终止空字符
    • --show-limits - 显示资源限制
    • -t, --verbose - 打印详细信息
    • -x, --exit - 如果超出 -s 选项的大小限制,则退出
    • --help - 显示帮助
    • --version - 显示版本
  • CMD - 命令;省略时默认为 echo
  • ARG - 初始参数列表;从标准输入中读取的参数会追加在此之后

#示例

基础使用

$ echo hello | xargs                    # 等价于 echo hello | xargs echo
hello

按行分割命令

$ echo -e "hello\nworld" | xargs        # 默认执行一次命令
hello world
$ echo -e "hello\nworld" | xargs -L 1   # 每 1 行执行一次命令
hello
world

按参数数量分割命令

$ echo 1 2 3 4 5 | xargs                # 默认执行一次命令
1 2 3 4 5
$ echo 1 2 3 4 5 | xargs -n 2           # 每两个参数执行一次命令
1 2
3 4
5

占位符替换

$ echo -e "eye\ntooth" | xargs -I {} echo 'A(n) {} for a(n) {}'             # 将 {} 替换为读取的参数,并且每一行执行一次命令
A(n) eye for a(n) eye
A(n) tooth for a(n) tooth
$ ls
1.txt  2.txt  3.txt
$ ls *.txt | xargs -I {} basename {} .txt | xargs -I {} mv {}.txt {}.md     # 将 .txt 文件批量重命名为 .md 文件
$ ls
1.md  2.md  3.md

#推荐阅读

#手册

更新: 2026/4/12

作者: PlanC

创建: 2026/4/12