如何删除目录中X个文件 [英] How to delete X number of files in a directory

查看:45
本文介绍了如何删除目录中X个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要获取目录中X个文件,我可以这样做:

To get X number of files in a directory, I can do:

$ ls -U | head -40000

那我该如何删除这40,000个文件?例如,类似:

How would I then delete these 40,000 files? For example, something like:

$ "rm -rf" (ls -U | head -40000)

推荐答案

您需要的工具是 xargs .它将标准输入转换为您指定命令的参数.输入的每一行都被视为单个参数.

The tool you need for this is xargs. It will convert standard input into arguments to a command that you specify. Each line of the input is treated as a single argument.

因此,类似的事情会起作用(不过,请参阅下面的注释,但通常不应以这种方式解析 ls ):

Thus, something like this would work (see the comment below, though, ls shouldn't be parsed this way normally):

ls -U | head -40000 | xargs rm -rf

我建议您先尝试使用较小的 head 大小开头,然后使用 xargs echo 打印输出的文件名,以便您了解要删除的内容.

I would recommend before trying this to start with a small head size and use xargs echo to print out the filenames being passed so you understand what you'll be deleting.

请注意,如果您的文件带有奇怪的字符,则有时可能会出现问题.如果您使用的是现代GNU系统,则还可能希望使用这些命令的参数,这些参数使用空字符分隔每个元素.由于文件名不能包含可安全解析所有可能名称的空字符.我不知道采用最简单的方法来将排名靠前的 X 个零分隔的项目.

Be aware if you have files with weird characters that this can sometimes be a problem. If you are on a modern GNU system you may also wish to use the arguments to these commands that use null characters to separate each element. Since a filename cannot contain a null character that will safely parse all possible names. I am not aware of a simple way to take the top X items when they are zero separated.

例如,您可以使用它来删除目录中的所有文件

So, for example you can use this to delete all files in a directory

find . -maxdepth 1 -print0 | xargs -0 rm -rf

这篇关于如何删除目录中X个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆