
在第 1 步中,我嘗試「尋找」目錄樹中最舊的文件,我透過以下方法解決了這個問題這個問題。
現在我想使用xargs
從最舊到最新的方式互動式刪除。
因為這find -type f -printf '%T+ %p\n' | sort | xargs -0 -d '\n' rm -i
不起作用。我在另一篇文章中看到
find . -type f -print0 | xargs -0 ls -rt
,但xargs
遺憾的是添加它不起作用。
pi@raspberrypi:/usr/share/doc/samba$ find . -type f -print0 | xargs -0 ls -rt | xargs -0 -d '\n' rm -i
rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.oc.IBM-DS’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema-netscapeds5.x.README’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema.IBMSecureWay’? rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema-FDS.ldif.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.at.IBM-DS.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba-nds.schema.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba.ldif.gz’? rm: remove write-protected regular file ‘./examples/LDAP/ol-schema-migrate.pl.gz’? rm: remove write-protected regular file ‘./examples/LDAP/get_next_oid’? rm: remove write-protected regular file ‘./README.Debian’? rm: remove write-protected regular file ‘./TODO.Debian’? rm: remove write-protected regular file ‘./NEWS.Debian.gz’? rm: remove write-protected regular file ‘./copyright’? rm: remove write-protected regular file ‘./changelog.Debian.gz’? rm: remove write-protected regular file ‘./examples/LDAP/README’?
請注意,這不是權限問題。我用/usr/share/doc/samba
這個例子來避免發布我的真實檔案名稱。
在網上搜索,我找不到任何遞歸(整個樹)、處理空白文件字元且互動的腳本。所以我做了這個。這不會處理所有類型的特殊字元。所以任何改進都會被接受。
#!/bin/bash
find -type f -printf '%T+ %p\n' | sort | head -n 3 > /tmp/1
cut -c32- /tmp/1 | awk '{print "rm -i", "\""$_"\""}'/tmp/2
bash /tmp/2
答案1
我在你的腳本中看到的唯一問題字元是"
和換行符。您不必太擔心檔案名稱中的換行符。
您可能想要使用不同的臨時檔案名,例如$$
在檔案名稱中新增 a 。
那麼,作為改進:
#!/bin/bash
TMP1=/tmp/file1.$$
TMP2=/tmp/file2.$$
find -type f -printf '%T+ %p\n' | sort | head -n 3 > $TMP1
cat $TMP1 | sed 's/"/\\"/g;s/[^ ]* //;s/^/rm -i "/;s/$/\"/' >$TMP2
bash $TMP2
rm -f $TMP1 $TMP2
這應該處理文件名中的引號。 (注意:腳本仍然存在一些問題。不過,在您自己的家庭環境中執行此操作是可以的。並且不建議使用大寫字母的 TMP,但無論如何我都會這樣做。)
注意:xargs -p
當您的檔案名稱中包含空格時,該功能將無法運作。
答案2
你就快到了。
這可以滿足您的要求並處理檔案名稱中的空格:
find -type f -printf '%T+ %p\n' | sort | cut -c32- | xargs -p -n1 -d '\n' rm
-p, --interactive
:提示使用者是否執行每個命令列並從終端機讀取一行。僅當回應以 y 或 Y 開頭時才執行命令列。
-n max-args, --max-args=max-args
:每個命令列最多使用 max-args 個參數。
-d delim
輸入項以指定字元結束。