Linux xargs 命令

2020-08-27  本文已影响0人  果蝇的小翅膀

简介

find /sbin -perm +700 |ls -l       #这个命令是错误的
find /sbin -perm +700 |xargs ls -l   #这样才是正确的

命令格式

somecommand |xargs -item command
参数:

实例命令

1. xargs 用作替换工具,读取输入数据重新格式化后输出。
定义一个测试文件,内有多行文本数据

cat test.txt

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

多行输入单行输出:

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 选项多行输出:

cat test.txt | xargs -n3

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 选项可以自定义一个定界符:

# echo "nameXnameXnameXname" | xargs -dX

name name name name

结合 -n 选项使用:

# echo "nameXnameXnameXname" | xargs -dX -n2

name name
name name

2. 控制输出格式。

xargs 的一个选项 -I,使用 -I 指定一个替换字符串 {},这个字符串在 xargs 扩展时会被替换掉,当 -I 与 xargs 结合使用,每一个参数命令都会被执行一次:

# cat arg.txt | xargs -I {} ./sk.sh -p {} -l

-p aaa -l
-p bbb -l
-p ccc -l

复制所有图片文件到 /data/images 目录下:

ls *.jpg | xargs -n1 -I {} cp {} /data/images

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

xargs 其他应用
假如你有一个文件包含了很多你希望下载的 URL,你能够使用 xargs下载所有链接:

cat url-list.txt | xargs wget -c

参考文献

  1. https://www.runoob.com/linux/linux-comm-xargs.html
上一篇 下一篇

猜你喜欢

热点阅读