xargs

发布时间 2024-01-13 16:22:28作者: 叶长尧

xargs

给其他命令传递参数的一个过滤器,又称管道命令,构造参数等。是给命令传递参数的一个过滤器,也是组合多个命令的一个工具 它把一个数据流分割为一些足够小的块,以方便过滤器和命令进行处理 。简单的说 就是把其他命令的给它的数据,传递给它后面的命令作为参数

选项

-d 为输入指定一个定制的分割符
-i 用 {} 代替 传递的数据
-I string 用string来代替传递的数据-n[数字] 设置每次传递几行数据
-n 选项限制单个命令行的参数个数
-t 显示执行详情
-p 交互模式
-P n 允许的最大线程数量为n
-s[大小] 设置传递参数的最大字节数(小于131072字节)
-x 大于 -s 设置的最大长度结束 xargs命令执行

案例

[root@localhost ~]# ls |grep .php |xargs -i mv {} {}.bak     #将当前目录下php文件,改名字
[root@localhost ~]# ls |grep .php |xargs -I {} mv {} {}.bak   #与上例相同
[root@localhost ~]# find ./ -name "*.tmp" | xargs -i rm -rf {}  #删除当前文件夹下的,tmp文件

---xargs -i 选项用法 {}代表的管道符前面传递的结果
[root@localhost130 yechangyao]# cp ./ttxt.txt{,.bak}
[root@localhost130 yechangyao]# ls
Centos-7.repo  cout_test.txt  Documents  epel-7.repo  hello.sh  news.txt  Public     test001.tar     test1108.txt  test3       test.txt      ttxt.txt      Videos
core.10299     Desktop        Downloads  expr.sh      Music     Pictures  Templates  test002.tar.gz  test2         testFor.sh  text1108.txt  ttxt.txt.bak  yechangyao
[root@localhost130 yechangyao]# find . -type f -name '*.bak'
./.cache/imsettings/log.bak
./yechangyao/1.log.bak
./ttxt.txt.bak
[root@localhost130 yechangyao]# find . -type f -name 'tt*.bak'
./ttxt.txt.bak
[root@localhost130 yechangyao]# find . -type f -name 'tt*.bak' | xargs -i rm -rf {}
[root@localhost130 yechangyao]# ls
Centos-7.repo  cout_test.txt  Documents  epel-7.repo  hello.sh  news.txt  Public     test001.tar     test1108.txt  test3       test.txt      ttxt.txt  yechangyao
core.10299     Desktop        Downloads  expr.sh      Music     Pictures  Templates  test002.tar.gz  test2         testFor.sh  text1108.txt  Videos
[root@localhost130 yechangyao]# 

结合 find 命令使用

xargs 结合 find 使用

用 rm 删除太多的文件时候,可能得到一个错误信息:/bin/rm Argument list too long. 用 xargs 去避免这个问题:

find . -type f -name "*.log" -print0 | xargs -0 rm -f

xargs -0 将 \0 作为定界符。

统计一个源代码目录中所有 php 文件的行数:

find . -type f -name "*.php" -print0 | xargs -0 wc -l

查找所有的 jpg 文件,并且压缩它们:

find . -type f -name "*.jpg" -print | xargs tar -czvf images.tar.gz

⚠️补充

与find结合使用效果和find选项(-exec和-ok)一样

-exec find命令对匹配的文件执行该参数所给出的其他linux命令。相应命令的形式为' 命令 - and' {} ;,注意{ }和\;之间的空格。
-ok 和- exec的作用相同,只不过和会人交互而已,OK执行前会向你确认是不是要执行。

找出自己家目录下所有的.txt文件并删除

find $HOME/. -name "*.txt" -ok rm {} \;

上例中, -ok 和 -exec 行为一样,不过它会给出提示,是否执行相应的操作。

查找当前目录下所有.txt文件并把他们拼接起来写入到all.txt文件中

find . -type f -name "*.txt" -exec cat {} \;> /all.txt