位置: 编程技术 - 正文
推荐整理分享linux find中的-print0和xargs中-0的奥妙(linux find -perm 详解),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:linux里find,linux find -cmin,linux find -mmin,linux find -cmin,linux find -atime,linux find -cmin,linux中的find的用法,linux find -perm,内容如对您有帮助,希望把文章链接给更多的朋友!
默认情况下, find 每输出一个文件名, 后面都会接着输出一个换行符 ('n'), 因此我们看到的 find 的输出都是一行一行的:
复制代码代码如下:[bash-4.1.5] ls -ltotal 0-rw-r--r-- 1 root root 0 -- : file1.log-rw-r--r-- 1 root root 0 -- : file2.log[bash-4.1.5] find -name '*.log'./file2.log./file1.log
比如我想把所有的 .log 文件删掉, 可以这样配合 xargs 一起用:
复制代码代码如下:[bash-4.1.5] find -name '*.log'./file2.log./file1.log[bash-4.1.5] find -name '*.log' | xargs rm[bash-4.1.5] find -name '*.log'
嗯, 不错, find+xargs 真的很强大. 然而:
复制代码代码如下:[bash-4.1.5] ls -ltotal 0-rw-r--r-- 1 root root 0 -- : file 1.log-rw-r--r-- 1 root root 0 -- : file 2.log[bash-4.1.5] find -name '*.log'./file 1.log./file 2.log[bash-4.1.5] find -name '*.log' | xargs rmrm: cannot remove `./file': No such file or directoryrm: cannot remove `1.log': No such file or directoryrm: cannot remove `./file': No such file or directoryrm: cannot remove `2.log': No such file or directory
原因其实很简单, xargs 默认是以空白字符 (空格, TAB, 换行符) 来分割记录的, 因此文件名 ./file 1.log 被解释成了两个记录 ./file 和 1.log, 不幸的是 rm 找不到这两个文件. 为了解决此类问题, 聪明的人想出了一个办法, 让 find 在打印出一个文件名之后接着输出一个 NULL 字符 ('') 而不是换行符, 然后再告诉 xargs 也用 NULL 字符来作为记录的分隔符. 这就是 find 的 -print0 和 xargs 的 -0 的来历吧.
复制代码代码如下:[bash-4.1.5] ls -ltotal 0-rw-r--r-- 1 root root 0 -- : file 1.log-rw-r--r-- 1 root root 0 -- : file 2.log[bash-4.1.5] find -name '*.log' -print0 | hd 0 1 2 3 4 5 6 7 8 9 A B C D E F |ABCDEF|--------+--+--+--+--+---+--+--+--+---+--+--+--+---+--+--+--+--+----------------|: 2e 2f 6c 2e 6c 6f 2e 2f |./file 1.log../f|: 6c 2e 6c 6f |ile 2.log. |[bash-4.1.5] find -name '*.log' -print0 | xargs -0 rm[bash-4.1.5] find -name '*.log'
你可能要问了, 为什么要选 '' 而不是其他字符做分隔符呢? 这个也容易理解: 一般的编程语言中都用 '' 来作为字符串的结束标志, 文件的路径名中不可能包含 '' 字符.
其他我收集的find、xargs实例:
删除以html结尾的天前的文件,包括带空格的文件:
复制代码代码如下:find /usr/local/backups -name "*.html" -mtime + -print0 |xargs -0 rm -rfvfind /usr/local/backups -mtime + -name "*.html" -exec rm -rf {} ;
find -print 和 -print0的区别:
-print 在每一个输出后会添加一个回车换行符,而-print0则不会。当前目录下文件从大到小排序(包括隐藏文件),文件名不为".":
find . -maxdepth 1 ! -name "." -print0 | xargs -0 du -b | sort -nr | head - | nl
nl:可以为输出列加上编号,与cat -n相似,但空行不编号以下功能同上,但不包括隐藏文件:
for file in *; do du -b "$file"; done|sort -nr|head -|nlx
args结合sed替换:
find . -name "*.txt" -print0 | xargs -0 sed -i 's/aaa/bbb/g'
xargs结合grep:
find . -name '*.txt' -type f -print0 |xargs -0 grep -n 'aaa' #“-n”输出行号
linux口令周期设置生效问题 前段时间根据公司要求对部分服务器进行安全加固,加固内容中有一项是要设置用户口令周期时间的。事实证明,这个木有任务用处。下面是在虚拟机
Linux下配置IPv6地址的方法 Linux在内核版本2.2.0以后就支持IPv6了,可查看/proc/net/if_inet6文件是否存在以确定你的系统是否支持IPv6如果没有,可尝试如下命令加载IPv6模组:#modprobeipv6
浅谈Linux系统性能监控常用命令 最近在给公司写项目运维手册。涉及到Linux系统的性能监控。现学现卖,边学边记录。下面几个是常用的命令。top复制代码代码如下:说明:查看当前的
友情链接: 武汉网站建设