2012-02-24 17 views
1

我正在運行find命令來獲取具有特定大小的文件列表,然後將輸出保存在文件中,現在我逐個遍歷該文件並詢問用戶哪一個他想刪除。我想要做一些事情,比如在列表中的每個文件旁邊添加一個數字,以便用戶可以直接輸入與此文件關聯的數字並刪除,而不必遍歷整個文件。請幫忙。將數字添加到由find命令返回的文件列表中

+2

爲什麼不循環'find'的輸出並詢問用戶?如果我理解正確,爲什麼不使用'find'..'exec' combo&use'rm -i'這是交互式刪除,它會在刪除文件之前詢問用戶[y/n]查詢。除非將文件用於除清單文件以外的其他內容,否則不需要將輸出保存到文件中 – 2012-02-24 11:33:17

回答

1
select f in $(find . -name '*.txt'); do 
    if [ -n "$f" ]; then 
     # put your command here 
     echo "rm $f" 
    fi 
done 
0
find . -size 5k -okdir rm {} ";" 

要求您爲每個文件,是否要執行的操作與否,沒有中間文件。

-okdir是一個Gnu擴展找到,並不適用於所有的實現。

另外,精益的方法是使用select

select fno in $(find . -size 5k); 
do 
    echo rm $fno 
done 

這是一個bashism,也許不是在你的shell存在。

help select顯示其用法。不幸的是,它也不像查找解決方案一樣允許一次選擇多個條目,但是您可以重複選擇一些內容,直到您點擊Ctrl + D,這很安靜舒適。

select: select NAME [in WORDS ... ;] do COMMANDS; done 

Select words from a list and execute commands. 

The WORDS are expanded, generating a list of words. The 
set of expanded words is printed on the standard error, each 
preceded by a number. If `in WORDS' is not present, `in "[email protected]"' 
is assumed. The PS3 prompt is then displayed and a line read 
from the standard input. If the line consists of the number 
corresponding to one of the displayed words, then NAME is set 
to that word. If the line is empty, WORDS and the prompt are 
redisplayed. If EOF is read, the command completes. Any other 
value read causes NAME to be set to null. The line read is saved 
in the variable REPLY. COMMANDS are executed after each selection 
until a break command is executed. 

Exit Status: 
Returns the status of the last command executed. 

這是什麼樣子:

select fno in *scala ; do echo "fno: " $fno; done 
1) Cartesian.scala  6) MWzufall.scala 
2) Haeufigkeit.scala  7) Shuffle.scala 
3) HelloChain.scala  8) eHWCChain.scala 
4) Lychrel.scala   9) equilibrum.scala  
5) M.scala    10) scala 
#? 3 
fno: HelloChain.scala 
#? 3 4 
fno: 
#? 

注意單詞用空格隔開,所以你要照顧在第二個例子,如果你在文件名中有空格的工作。

相關問題