首页 > 系统服务 > 详细

Shell之Xargs命令

时间:2019-09-29 16:22:22      阅读:86      评论:0      收藏:0      [点我收藏+]

Shell之Xargs命令

?? Written by Zak Zhu

学习python风格, 优雅规范书写shell代码

参考

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实例说明

  1. xargs后面的命令默认是echo

    echo "hello world !" | xargs

    技术分享图片

  2. 从文件中一行行读取文件名并创建

    cat filenames | xargs -t -d "\n" touch

    技术分享图片

  3. 查找日志文件(文件名包含空格)并删除

    思路:

    • find命令查找出以.log结尾的文件, 考虑到文件名可能包含空格, 用-print0参数把找到的文件以null分隔
    • xargs命令的-0参数用null作分隔符, 然后删除
    find /tmp -name "*.log" -type f -print0 | xargs -t -0 rm

    技术分享图片

  4. 把以.py结尾的文件, 修改成.py.bak结尾

    ls *.py | xargs -t -I {} mv {} {}.bak

    技术分享图片

  5. 读取输入数据重新格式化后输出

    cat test | xargs -n 3

    技术分享图片

  6. xargs在传参前逐个提示确认

    ls /tmp | xargs -n 1 -p rm -rf

    技术分享图片

Shell之Xargs命令

原文:https://www.cnblogs.com/zakzhu/p/11607914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!