V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fsckzy
V2EX  ›  FreeBSD

如何优化这一条 shell?

  •  
  •   fsckzy · 2016-02-14 09:39:41 +08:00 · 5436 次点击
    这是一个创建于 2965 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有 500 个文件夹,每个文件夹里面都有一个 cache 目录,现在要把这 500 个 cache 里面的文件全部删掉

    删除这个目录
    find . -name 'cache' -type d -exec rm {} \;
    批量创建 cache 文件夹
    mkdir -pv xx{0..9}/cache #如果文件名有规律的, xx1 , xx2 的用这条,没有规律的用下面那条
    for F in `ls -al|grep '^d'`;do cp -rf /root/cache/ $F ; done

    但是觉得这样太费劲了。还有别的办法吗?
    9 条回复    2016-02-14 17:01:08 +08:00
    yangqi
        1
    yangqi  
       2016-02-14 09:45:34 +08:00
    find . -path 'cache/*' -type f -exec rm {} \;
    yangqi
        2
    yangqi  
       2016-02-14 09:46:04 +08:00
    直接删文件就行了
    yangqi
        3
    yangqi  
       2016-02-14 09:49:12 +08:00
    纠正一下

    find . -path '*/cache/*' -type f -exec rm {} \;
    zxb
        4
    zxb  
       2016-02-14 09:58:43 +08:00 via Android   ❤️ 2
    rm */cache/*
    acoada
        5
    acoada  
       2016-02-14 09:59:41 +08:00 via iPhone
    试了一下,
    创建了相应的目录和文件之后,
    find . -name 'cache' -type d -exec rm {}/* \;
    rm: cannot remove ‘./xx1/cache/*’: No such file or directory

    这个错误挺有意思的,
    是因为 * 没有被 bash 展开导致的吗?
    elvodn
        6
    elvodn  
       2016-02-14 10:16:51 +08:00
    @acoada find . -name 'cache' -type d -exec /bin/sh -c "rm {}/*" \;
    這樣寫就可以
    luw2007
        7
    luw2007  
       2016-02-14 10:20:04 +08:00
    @zxb 的回复是最简单的。
    rm */cache/*
    xderam
        8
    xderam  
       2016-02-14 14:46:55 +08:00
    可以用 rsync 也很省事。。而且听说比 rm 快。
    fsckzy
        9
    fsckzy  
    OP
       2016-02-14 17:01:08 +08:00
    @zxb 在目录都是一样的情况下,你的是最简单的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2844 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:22 · PVG 23:22 · LAX 08:22 · JFK 11:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.