如何限制在 bash 中查找命令的结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28413735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:20:56  来源:igfitidea点击:

How do I limit the results of the command find in bash?

bashfind

提问by Mariano Vedovato

The following command:

以下命令:

find . -name "file2015-0*" -exec mv {} .. \;

Affects about 1500 results. One by one they move a previous level.

影响大约 1500 个结果。他们一个接一个地往上一层。

If I would that the results not exceeds for example in 400? How could I?

如果我希望结果不超过例如 400?我怎么能?

回答by Tiago Lopo

You can do this:

你可以这样做:

 find . -name "file2015-0*" | head -400 | xargs -I filename mv  filename ..

If you want to simulate what it does use echo:

如果你想模拟它的用途echo

 find . -name "file2015-0*" | head -400 | xargs -I filename echo mv  filename ..

回答by fedorqui 'SO stop harming'

You can for example provide the findoutput into a while readloop and keep track with a counter:

例如,您可以将find输出提供到while read循环中并使用计数器进行跟踪:

counter=1
while IFS= read -r file
do
   [ "$counter" -ge 400 ] && exit
   mv "$file" ..
   ((counter++))
done < <(find . -name "file2015-0*")

Note this can lead to problems if the file name contains new lines... which is quite unlikely. Also, note the mvcommand is now moving to the upper level. If you want it to be related to the path of the dir, some bash conversion can make it.

请注意,如果文件名包含新行,这可能会导致问题......这是不太可能的。另外,请注意该mv命令现在正在移动到上层。如果您希望它与目录的路径相关,则可以进行一些bash转换。