xargs(英文全拼: eXtended ARGuments)是一个用于传递参数的过滤器,同时也是组合多个命令的强大工具。
它能够将管道或标准输入(stdin)中的数据转换为命令行参数,也可以从文件输出中读取信息进行处理。
xargs 还可以实现文本格式的转换,比如将多行内容合并为单行或将单行拆分为多行。
默认情况下,xargs 使用 echo 命令,这意味着原本包含换行和空白的输入在经过 xargs 处理后会被空格代替。
作为一款功能强大的命令,xargs 可以捕获一个命令的输出,并将其传递给另一个命令进行后续操作。
为什么我们需要这个命令?因为许多命令并不支持通过管道 | 传递参数,但在实际工作中又经常需要这样的功能。例如:
<pre class="brush:php;toolbar:false">find /sbin -perm +700 |ls -l #这是一个错误示例 find /sbin -perm +700 |xargs ls -l #这才是正确用法
通常来说,xargs 是与管道一起配合使用的。
基本格式:
<pre class="brush:php;toolbar:false">somecommand |xargs -item command
常用选项:
xargs 可以作为替换工具,对输入数据重新格式化后再输出。
创建一个测试文件,其中包含多行文本内容:
<pre class="brush:php;toolbar:false"># cat test.txt <p>a b c d e f g h i j k l m n o p q r s t u v w x y z
多行输入转为单行输出:
<pre class="brush:php;toolbar:false"># cat test.txt | xargs a b c d e f g h i j k l m n o p q r s t u v w x y z
使用 -n 参数实现按组分行输出:
<pre class="brush:php;toolbar:false"># cat test.txt | xargs -n3</p><p>a b c d e f g h i j k l m n o p q r s t u v w x y z
-d 参数允许自定义分隔符:
<pre class="brush:php;toolbar:false"># echo "nameXnameXnameXname" | xargs -dX</p><p>name name name name
结合 -n 参数使用自定义分隔符:
<pre class="brush:php;toolbar:false"># echo "nameXnameXnameXname" | xargs -dX -n2</p><p>name name name name
从标准输入读取数据,并将格式化后的参数传递给指定命令
假设存在脚本 sk.sh 和参数文件 arg.txt:
<pre class="brush:php;toolbar:false">#!/bin/bash</p><h1>sk.sh 脚本内容,用于打印所有传入参数</h1><p>echo $*
arg.txt 文件内容如下:
<pre class="brush:php;toolbar:false"># cat arg.txt</p><p>aaa bbb ccc
利用 xargs 的 -I 参数,可指定替换字符串 {},该字符串在扩展时会被实际参数替代,且每个参数都会触发一次命令执行:
<pre class="brush:php;toolbar:false"># cat arg.txt | xargs -I {} ./sk.sh -p {} -l</p><p>-p aaa -l -p bbb -l -p ccc -l
批量复制图片文件至目标目录:
<pre class="brush:php;toolbar:false">ls <em>.jpg | xargs -n1 -I {} cp {} /data/images
xargs 与 find 命令结合使用
在删除大量文件时可能会遇到错误提示:/bin/rm Argument list too long. 此时可通过 xargs 解决:
<pre class="brush:php;toolbar:false">find . -type f -name "</em>.log" -print0 | xargs -0 rm -f
这里 -0 参数指定了 \0 字符作为定界符。
统计某个源代码目录下所有 php 文件的总行数:
<pre class="brush:php;toolbar:false">find . -type f -name "<em>.php" -print0 | xargs -0 wc -l
查找所有 jpg 图片文件并对它们进行压缩:
<pre class="brush:php;toolbar:false">find . -type f -name "</em>.jpg" -print | xargs tar -czvf images.tar.gz
xargs 的其他实用场景
如果你有一个包含多个待下载链接的文件,可以通过 xargs 快速完成任务:
<pre class="brush:php;toolbar:false"># cat url-list.txt | xargs wget -c
以上就是linux构建并执行命令行参数是什么-xargs 命令使用与实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号