Shell之Xargs命令

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
    

    1

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

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

    2

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

    思路:

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

    3

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

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

    4

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

    cat test | xargs -n 3
    

    5

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

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

    6

posted @ 2019-09-29 15:04  ZakZhu  阅读(673)  评论(0编辑  收藏  举报