Shell之Xargs命令
Shell之Xargs命令
😄 Written by Zak Zhu
学习python风格, 优雅规范书写shell代码
参考
- 菜鸟教程/Linux xargs命令(https://www.runoob.com/linux/linux-comm-xargs.html)
- 程序猿小卡_casper/Linux基础: xargs命令(https://segmentfault.com/a/1190000012566053)
- xargs命令_Linux xargs命令: 一个给其他命令传递参数的过滤器(http://c.biancheng.net/linux/xargs.html)
- 阮一峰的网络日志/xargs 命令教程(https://www.ruanyifeng.com/blog/2019/08/xargs-tutorial.html)
- Ein Verne/每天学习一个命令: xargs(http://einverne.github.io/post/2019/06/xargs.html)
xargs命令简介
xargs
reads items from the standard input, delimited by blanks or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input.
xargs命令格式
语法:
SOMECOMMAND | xargs [OPTION]... COMMAND [INITIAL-ARGS]...
参数:
-0, --null # Input items are terminated by a null, not whitespace
-d CHAR, --delimiter=CHAR # Input items are terminated by the specified character
-I R # replace 'R' in INITIAL-ARGS with names read from standard input; if 'R' is unspecified, assume '{}'
-n X # use X arguments per command
-p # prompt before runing commands
-t, --verbose # print commands before executing them
xargs实例说明
-
xargs后面的命令默认是echo
echo "hello world !" | xargs
-
从文件中一行行读取文件名并创建
cat filenames | xargs -t -d "\n" touch
-
查找日志文件(文件名包含空格)并删除
思路:
- find命令查找出以.log结尾的文件, 考虑到文件名可能包含空格, 用-print0参数把找到的文件以null分隔
- xargs命令的-0参数用null作分隔符, 然后删除
find /tmp -name "*.log" -type f -print0 | xargs -t -0 rm
-
把以.py结尾的文件, 修改成.py.bak结尾
ls *.py | xargs -t -I {} mv {} {}.bak
-
读取输入数据重新格式化后输出
cat test | xargs -n 3
-
xargs在传参前逐个提示确认
ls /tmp | xargs -n 1 -p rm -rf