五月综合激情婷婷六月,日韩欧美国产一区不卡,他扒开我内裤强吻我下面视频 ,无套内射无矿码免费看黄,天天躁,日日躁,狠狠躁

新聞動態(tài)

linux find中的-print0和xargs中-0的奧妙

發(fā)布日期:2022-03-11 08:50 | 文章來源:腳本之家

默認情況下, find 每輸出一個文件名, 后面都會接著輸出一個換行符 ('n'), 因此我們看到的 find 的輸出都是一行一行的:


復制代碼
代碼如下:

[bash-4.1.5] 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
[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 -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
[bash-4.1.5] find -name '*.log'
./file 1.log
./file 2.log
[bash-4.1.5] 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 的來歷吧.


復制代碼
代碼如下:

[bash-4.1.5] 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
[bash-4.1.5] find -name '*.log' -print0 | hd
0 1 2 34 5 6 78 9 A BC D E F |0123456789ABCDEF|
--------+--+--+--+--+---+--+--+--+---+--+--+--+---+--+--+--+--+----------------|
00000000: 2e 2f 66 69 6c 65 20 31 2e 6c 6f 67 00 2e 2f 66 |./file 1.log../f|
00000010: 69 6c 65 20 32 2e 6c 6f 67 00|ile 2.log.|
[bash-4.1.5] find -name '*.log' -print0 | xargs -0 rm
[bash-4.1.5] find -name '*.log'

你可能要問了, 為什么要選 '' 而不是其他字符做分隔符呢? 這個也容易理解: 一般的編程語言中都用 '' 來作為字符串的結束標志, 文件的路徑名中不可能包含 '' 字符.

其他我收集的find、xargs實例:

刪除以html結尾的10天前的文件,包括帶空格的文件:


復制代碼
代碼如下:

find /usr/local/backups -name "*.html" -mtime +10 -print0 |xargs -0 rm -rfvfind /usr/local/backups -mtime +10 -name "*.html" -exec rm -rf {} ;

find -print 和 -print0的區(qū)別:

-print 在每一個輸出后會添加一個回車換行符,而-print0則不會。
當前目錄下文件從大到小排序(包括隱藏文件),文件名不為".":

find . -maxdepth 1 ! -name "." -print0 | xargs -0 du -b | sort -nr | head -10 | nl

nl:可以為輸出列加上編號,與cat -n相似,但空行不編號
以下功能同上,但不包括隱藏文件:

for file in *; do du -b "$file"; done|sort -nr|head -10|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”輸出行號

香港快速服務器

版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網友推薦、互聯(lián)網收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。

實時開通

自選配置、實時開通

免備案

全球線路精選!

全天候客戶服務

7x24全年不間斷在線

專屬顧問服務

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務熱線

關注
微信

關注官方微信
頂部