我想知道如何編寫一個小腳本來刪除小於50千字節但我沒有成功的文本文件。shell腳本刪除小於x kb的文件
我的嘗試是這樣的:
#!/bin/bash
for i in *.txt
do
if [ stat -c %s < 5 ]
then
rm $i
fi
done
我將一些並欣賞的指導,謝謝!
我想知道如何編寫一個小腳本來刪除小於50千字節但我沒有成功的文本文件。shell腳本刪除小於x kb的文件
我的嘗試是這樣的:
#!/bin/bash
for i in *.txt
do
if [ stat -c %s < 5 ]
then
rm $i
fi
done
我將一些並欣賞的指導,謝謝!
您應該使用fedorqui的版本,但以供參考:
#!/bin/bash
for i in ./*.txt # ./ avoids some edge cases when files start with dashes
do
# $(..) can be used to get the output of a command
# use -le, not <, for comparing numbers
# 5 != 50k
if [ "$(stat -c %s "$i")" -le 50000 ]
then
rm "$i" # specify the file to delete
fi # end the if statement
done
它通常比較容易寫一塊和驗證程序片段,每個部分的作品,而不是寫整個程序,然後試圖調試它。
您可以直接使用find
與size
選項是:
find /your/path -name "*.txt" -size -50k -delete
^^^^^^^^^^
if you wanted bigger than 50k, you'd say +50
你可能要堅持到當前目錄下的文件,而無需在目錄結構中下降。如果是這樣,你可以說:
find /your/path -maxdepth 1 -name "*.txt" -size -50k -delete
從man find
:
-size N [cwbkMG]
文件使用的空間n個單位。以下後綴可以使用:
「B」爲512字節的塊(這是如果沒有使用後綴缺省值)
「C」爲字節
「W」爲兩個字節的詞語
數 'k' 爲千字節(1024個字節爲單位)
'M' 爲兆字節(1048576個字節爲單位)
'G' 爲千兆字節(的1073741824個字節的單元)
這是很快的+1 – whoan
注意你的'if'語句不包含關閉'fi'。 – fedorqui
另請參閱超級用戶上的[如何查找大於/小於x字節的文件?](http://superuser.com/q/204564/173513)。 – jww