在Linux终端中,如何删除一个或两个目录中的所有文件 [英] In Linux terminal, how to delete all files in a directory except one or two

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

问题描述

在Linux终端中,如何从一个文件夹中删除除了一两个文件夹以外的所有文件?



例如。

我在一个目录和一个 .txt 文件中有 100 图像文件。
我想删除除 .txt 文件以外的所有文件。

解决方案

在目录中列出文件,过滤掉所有不包含保留文件的文件,并删除列表中的所有文件。

  ls | grep -v'文件保留'| xargs rm 

为了避免文件名空间的问题(记住永远不要在文件名中使用空格) code> find 和 -0 选项。

  find'path'-maxdepth 1 -not -name'file-to-keep'-print0 | xargs -0 rm 

或者混合使用 grep 选项 -z find 管理 -print0 c>


In a Linux terminal, how to delete all files from a folder except one or two?

For example.

I have 100 image files in a directory and one .txt file. I want to delete all files except that .txt file.

解决方案

From within the directory, list the files, filter out all not containing 'file-to-keep', and remove all files left on the list.

ls | grep -v 'file-to-keep' | xargs rm

To avoid issues with spaces in filenames (remember to never use spaces in filenames), use find and -0 option.

find 'path' -maxdepth 1 -not -name 'file-to-keep' -print0 | xargs -0 rm

Or mixing both, use grep option -z to manage the -print0 names from find

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

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