xargs详解

一、场景

这个命令是错误的

find ./ -perm +700 |ls -l

这样才是正确的

find ./ -perm +700 |xargs ls -l 

 二、用法

[root@localhost tmp]# xargs --help
Usage: xargs [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]
       [-E eof-str] [-e[eof-str]]  [--eof[=eof-str]]
       [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]
       [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]
       [-n max-args] [--max-args=max-args]
       [-s max-chars] [--max-chars=max-chars]
       [-P max-procs]  [--max-procs=max-procs] [--show-limits]
       [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]
       [--version] [--help] [command [initial-arguments]]

Report bugs to <bug-findutils@gnu.org>.

 三、示例

1、压缩所有的日志文件到每一个文件

find ./ -type f  -name "*.log" | xargs -i -t  tar -zcvf {}.tar.gz {}

 2、压缩所有的图片文件到一个文件

find ./ -name *.jpg -type f -print | xargs tar -zcvf images.tar.gz

 3、文件内容替换

find ./ -maxdepth 2 -name a -print | xargs -t -i sed -i '1 i111' '{}'

 4、权限修改

find ./ -perm -7 -print | xargs chmod o-w

 5、查看文件类型

find ./ -type f -print | xargs file

 6、删除多个文件

find ./ -name "*.log" -print0 | xargs -i -0 rm -f {}

 7、复制多个文件

find ./ -type f -name "*.txt" | xargs -i cp {}  /tmp/
find ./ -type f -name "*.txt" | xargs -I {} cp {}  /tmp/

三、注意事项

1、加-i 参数直接用 {}就能代替管道之前的标准输出的内容;加 -I 参数 需要事先指定替换字符

2、cshell和tcshell中,需要将{}用单引号、双引号或反斜杠

3、如果需要处理特殊字符,需要使用-0参数进行处理

原文地址:https://www.cnblogs.com/chenpingzhao/p/4623799.html