2012-06-25 42 views
89

我試圖制定一個刪除超過15天的sql文件的命令。命令行:管道找到rm的結果

查找部分工作,但不是rm。

rm -f | find -L /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups -type f \(-name '*.sql' \) -mtime +15 

它踢出了我想要刪除的文件的清單,但不刪除它們。路徑是正確的。

usage: rm [-f | -i] [-dIPRrvW] file ... 
     unlink file 
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120601.backup.sql 
... 
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120610.backup.sql 

我在做什麼錯?

回答

186

您實際上是管道rm輸出輸入find。你想要的是使用的find參數輸出到rm

find -type f -name '*.sql' -mtime +15 | xargs rm 

xargs是命令「皈依」的標準輸入到另一個程序的參數,或者,因爲它們更準確地把它放在從標準輸入man頁,

構建和執行命令行

請注意,如果文件名可以包含空格字符,您應該爲糾正:

find -type f -name '*.sql' -mtime +15 -print0 | xargs -0 rm 

但實際上,find有這個快捷方式:在-delete選項:

find -type f -name '*.sql' -mtime +15 -delete 

請注意的以下警告在man find

Warnings: Don't forget that the find command line is evaluated 
    as an expression, so putting -delete first will make find try to 
    delete everything below the starting points you specified. When 
    testing a find command line that you later intend to use with 
    -delete, you should explicitly specify -depth in order to avoid 
    later surprises. Because -delete implies -depth, you cannot 
    usefully use -prune and -delete together. 

PS請注意,直接管道到rm不是一個選項,因爲rm不希望標準輸入上的文件名。你現在正在做的是把它們倒過來。

+1

謝謝。我閱讀了手冊頁並試了一下這個標誌。我正在傳遞一個完整路徑,但找回「/ usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups /:相對路徑可能不安全」。任何想法爲什麼? – jerrygarciuh

+1

@jerrygarciuh看看[這裏](http://www.mail-archive.com/[email protected]/msg16944.html)。 –

+0

謝謝。我不知道我是否很好地跟蹤了這篇文章,但是當我模擬他們的解決方案並且在命令的末尾放置了-delete時,它刪除了所有的sql文件,而不管mod時間如何......但它沒有警告,所以我猜測這是進步...... – jerrygarciuh

19
find /usr/www/bar/htdocs -mtime +15 -exec rm {} \; 

將在/usr/www/bar/htdocs超過15天選擇文件並刪除它們。

0

另一個更簡單的方法是使用locate命令。使用它xargs

例如,

locate file.txt | xargs rm 
locate *something* | xargs rm 
0

假設你是不是在包含* .SQL備份文件的目錄:

find /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/*.sql -mtime +15 -exec rm -v {} \; 

以上-v選項是很方便的將它輸出冗長哪些文件正在被刪除,因爲它們被刪除。

我喜歡列出將要首先刪除的文件。 E.g:

find /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/*.sql -mtime +15 -exec ls -lrth {} \;