zoukankan      html  css  js  c++  java
  • Linux xargs

    产生命令的参数。常和find 在一起连用。

    1. echo 'one two three' | xargs mkdir

    2. find /tmp -mtime +14 | xargs rm

    3. time find . -type f -name "*.txt" -exec rm {} ; 0.35s user 0.11s system 99% cpu 0.467 total

    time find ./foo -type f -name "*.txt" | xargs rm 0.00s user 0.01s system 75% cpu 0.016 total

    4. echo 'one two three' | xargs -t rm

    5. echo 'one two three' | xargs -p touch

    6. cat foo.txt | xargs -I % sh -c 'echo %; mkdir %'

    读取stdin,将格式化后的参数传递给命令

    假设一个命令为 xgj.sh 和一个保存参数的文件args.txt:

    args.txt已经具备执行权限

    [root@entel2 test]# cat xgj.sh 
    #!/bin/bash
    #打印所有的参数
    echo $*
    [root@entel2 test]# cat args.txt 
    aaa
    bbb
    ccc
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    xargs的一个选项-I,

    使用-I指定一个替换字符串{},

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

    [root@entel2 test]# cat args.txt | xargs -I {} ./xgj.sh XXX {} YYY
    XXX aaa YYY
    XXX bbb YYY
    XXX ccc YYY
    • 1
    • 2
    • 3
    • 4

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

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

    xargs结合find使用

    用rm 删除太多的文件时候,可能得到一个错误信息: 
    /bin/rm Argument list too long.

    用xargs去避免这个问题:

     find . -type f -name "*.log" -print0 | xargs -0 rm -f 
    • 1

    xargs -0将作为定界符。

    -0 这个参数可以将,空格等字符还原成一般字符。

    统计一个源代码目录中所有py文件的行数:

     find . -type f -name "*.py" -print0 | xargs -0 wc -l 
    • 1

    查找所有的jpg 文件,并且压缩它们:

     find . -type f -name "*.jpg" -print | xargs tar -czvf images.tar.gz 
    • 1

    xargs其他应用

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

     cat url-list.txt | xargs wget -c 
  • 相关阅读:
    (剑指offer)斐波那契数列
    手写Vue源码 watch的实现
    Vue源码之异步批量任务更新
    手写Vue源码之 依赖收集
    C# 测试代码#if DEBUG使用
    shell脚本编程相关7
    C#中关于ref和out的认识
    shell脚本编程相关6
    shell脚本编程相关5
    shell脚本编程相关4
  • 原文地址:https://www.cnblogs.com/zwingblog/p/8467161.html
Copyright © 2011-2022 走看看