• Linux:find命令中


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

    ls -l
    total 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.log
    
    find -name '*.log' | xargs rmfind -name '*.log'

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

    ls -l
    total 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.log
    
    find -name '*.log'
    ./file 1.log
    ./file 2.log
    
    find -name '*.log' | xargs rm
    rm: cannot remove `./file': No such file or directory
    rm: cannot remove `1.log': No such file or directory
    rm: cannot remove `./file': No such file or directory
    rm: 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 的来历吧.

    ls -l
    total 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.log
    find -name '*.log' -print0 | xargs -0 rmfind -name '*.log'

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

  • 相关阅读:
    爬虫(七):爬取猫眼电影top100
    爬虫(六):Selenium库使用
    爬虫(五):PyQuery的使用
    爬虫(四):BeautifulSoup库的使用
    爬虫(三):Requests库的基本使用
    爬虫(一):基本原理
    爬虫(二):Urllib库详解
    安装mongodb
    利用 Chromium Embedded Framework (CEF) 定制提取 Flash 视频的浏览器
    Flash Player 19.0.0.124 Beta + IHTMLDocument3 IHTMLDocument2 ->get_innerHTML
  • 原文地址:https://www.cnblogs.com/xwb583312435/p/9020224.html
Copyright © 2020-2023  润新知