博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linux:find命令中
阅读量:4707 次
发布时间:2019-06-10

本文共 1353 字,大约阅读时间需要 4 分钟。

默认情况下, find 每输出一个文件名, 后面都会接着输出一个换行符 ('\n'), 因此我们看到的 find 的输出都是一行一行的:

ls -ltotal 0-rw-r--r-- 1 root root 0 2010-08-02 18:09 file1.log-rw-r--r-- 1 root root 0 2010-08-02 18:09 file2.log find -name '*.log'./file2.log./file1.log

比如我想把所有的 .log 文件删掉, 可以这样配合 xargs 一起用:

find -name '*.log'./file2.log./file1.logfind -name '*.log' | xargs rmfind -name '*.log'

嗯, 不错, find+xargs 真的很强大. 然而:

ls -ltotal 0-rw-r--r-- 1 root root 0 2010-08-02 18:12 file 1.log-rw-r--r-- 1 root root 0 2010-08-02 18:12 file 2.logfind -name '*.log'./file 1.log./file 2.logfind -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 字符 ('\0') 而不是换行符, 然后再告诉 xargs 也用 NULL 字符来作为记录的分隔符. 这就是 find 的 -print0 和 xargs 的 -0 的来历吧.

ls -ltotal 0-rw-r--r-- 1 root root 0 2010-08-02 18:12 file 1.log-rw-r--r-- 1 root root 0 2010-08-02 18:12 file 2.logfind -name '*.log' -print0 | xargs -0 rmfind -name '*.log'

你可能要问了, 为什么要选 '\0' 而不是其他字符做分隔符呢? 这个也容易理解: 一般的编程语言中都用 '\0' 来作为字符串的结束标志, 文件的路径名中不可能包含 '\0' 字符.

转载于:https://www.cnblogs.com/xwb583312435/p/9020224.html

你可能感兴趣的文章
10要点解决IE6兼容性问题
查看>>
Seven Python Tools All Data Scientists Should Know How to Use
查看>>
cocos2d-x学习之路(二)——分析AppDelegate和HelloWorldScene文件
查看>>
Asp.net 对于服务器控件添加Client端方法
查看>>
在Salesforce中创建Approval Process
查看>>
NFS服务搭建与配置
查看>>
python计算文件md5值
查看>>
android 4.1 Emulator Skins
查看>>
Web站点防注入注意事项(转)
查看>>
第0次作业
查看>>
广播接收器——接收系统广播
查看>>
亿能测试资讯_2013-8-11
查看>>
北京地铁月度消费总金额计算(Python版)
查看>>
nginx+tomcat配置https
查看>>
[hadoop]备份
查看>>
C#中的委托和事件(续)
查看>>
python--MySql
查看>>
机器学习 - pycharm, pyspark, spark集成篇
查看>>
mysql explain 中key_len的计算
查看>>
实验一
查看>>