将数字添加到由find命令返回的文件列表中
问题描述:
我正在运行find命令来获取具有特定大小的文件列表,然后将输出保存在文件中,现在我逐个遍历该文件并询问用户哪一个他想删除。我想要做一些事情,比如在列表中的每个文件旁边添加一个数字,以便用户可以直接输入与此文件关联的数字并删除,而不必遍历整个文件。请帮忙。将数字添加到由find命令返回的文件列表中
答
select f in $(find . -name '*.txt'); do
if [ -n "$f" ]; then
# put your command here
echo "rm $f"
fi
done
答
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:
#?
注意单词用空格隔开,所以你要照顾在第二个例子,如果你在文件名中有空格的工作。
为什么不循环'find'的输出并询问用户?如果我理解正确,为什么不使用'find'..'exec' combo&use'rm -i'这是交互式删除,它会在删除文件之前询问用户[y/n]查询。除非将文件用于除清单文件以外的其他内容,否则不需要将输出保存到文件中 – 2012-02-24 11:33:17