find & rm & cp组合

来源:互联网 发布:淘宝店被永久封了 攻略 编辑:程序博客网 时间:2024/05/26 17:44

find & rm & cp组合

1. find & rm

用xargs处理带空格文件名

find和xargs是最好的组合,可以说是linux shell下的瑞士军刀,用xargs配合find,比直接用find的-exec参数,速度更快,用法也更直观。
基本的用法比如:

find ./ -name ‘*.bak’ | xargs rm -rf

一般情况,上面这个命令运行的很好,但是如果找到的文件名代空格,上面的命令运行就可能会出问题了。

find有一个参数-print0,于默认的-print相比,输出的序列不是以空格分隔,而是以null字符分隔。而xargs也有一个参数-0,可以接受以null而非空格间隔的输入流。所以说xargs简直就是为find而生的。上面的问题就很好解决了:

find ./ -name ‘*.bak’ -print0 | xargs -0 rm -rf

OR

find . -name “*.bak”|xargs -i echo ‘”{}”’ |xargs rm -rf

OR

sudo find ./ -name ‘*.bak’ -print0 | xargs -0 sudo rm -rf {} # 带有空格的目录

example:

find /home/sean/work/openwrt_ath/build_dir/target-mips_34kc_uClibc-0.9.33.2/openconnect-7.06/ -name config.guess | xargs -r chmod u+w; find /home/sean/work/openwrt_ath/build_dir/target-mips_34kc_uClibc-0.9.33.2/openconnect-7.06/ -name config.guess | xargs -r -n1 cp --remove-destination /home/sean/work/openwrt_ath/scripts/config.guess; find /home/sean/work/openwrt_ath/build_dir/target-mips_34kc_uClibc-0.9.33.2/openconnect-7.06/ -name config.sub | xargs -r chmod u+w; find /home/sean/work/openwrt_ath/build_dir/target-mips_34kc_uClibc-0.9.33.2/openconnect-7.06/ -name config.sub | xargs -r -n1 cp --remove-destination /home/sean/work/openwrt_ath/scripts/config.subfind /home/sean/work/openwrt_ath/build_dir/target-mips_34kc_uClibc-0.9.33.2/openconnect-7.06/ipkg-ar71xx/openconnect -name 'CVS' -o -name '.svn' -o -name '.#*' -o -name '*~'| xargs -r rm -rf

2. find & cp

find . -name ‘.so’ -o ‘.a’ |xargs -I {} cp -r {} /tmp