简体   繁体   English

在Linux脚本中,如何删除当前目录中的所有文件和目录?

[英]In a Linux script, how to remove all files & directories but one, in current directory?

In a shell script, I want to remove all files and directories but one file, in the current directory. 在shell脚本中,我想删除当前目录中的所有文件和目录,但删除一个文件。 I used 我用了

 ls | grep -v 'nameoffiletokeep' | xargs rm

this removes files, but directories are not deleted. 这将删除文件,但不会删除目录。

find . -mindepth 1 -maxdepth 1 ! -iname nameoffiletokeep -print0| xargs -0 rm -rf;

This finds all files and directories that are direct children of the current working directory that are not named nameoffiletokeep and removes them all (recursively for directories), regardless of leading dots (eg .hidden , which would be missed if you used a glob like rm -rf * ), spaces, or other metachars in the file names. 这个发现是命名当前工作目录的直接孩子的所有文件和目录nameoffiletokeep并删除它们所有(递归目录),无论领导点(如.hidden ,如果你使用的水珠像这将错过rm -rf * ),文件名中的空格或其他元字符。

I've used -iname for case-insensitive matching against nameoffiletokeep , but if you want case-sensitivity, you should use -name . 我已经使用-inamenameoffiletokeep进行不区分大小写的匹配,但是如果要区分大小写,则应该使用-name The choice should depend on the underlying file system behavior, and your awareness of the letter-case of the file name you're trying to protect. 选择应取决于基础文件系统的行为以及您对要保护的文件名字母大小写的了解。

If you are using bash, you can use extended globbing: 如果您正在使用bash,则可以使用扩展的globbing:

shopt -s extglob
rm -fr !(nameoffiletokeep)

In zsh the same idea is possible: 在zsh中,相同的想法是可能的:

setopt extended_glob
rm -fr ^nameoffiletokeep

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写将一个目录下的所有文件和目录复制到另一个目录的linux脚本? - How to write a linux script that copies all the files and directories under one directory to another directory? 如何在Linux中的所有子目录上强制CURRENT目录权限? - How to force CURRENT directory permissions on all sub-directories in Linux? 如何在Linux中重命名当前目录中的所有文件 - How to rename all the files in current directory in linux 仅删除linux目录中的文件而不是目录 - Remove only files in directory on linux NOT directories 如何删除所有非单一文件的Linux目录? - How to remove all not single files Linux directory? Linux:如何删除目录本身(不是子目录)内的所有文件(不是目录) - Linux: How to delete all of the files (not directories) inside a directory itself (not childs) 如何编写UNIX命令或脚本来删除当前目录下所有子文件夹中相同类型的文件? - How to write a unix command or script to remove files of the same type in all sub-folders under current directory? 如何在 Linux 上找到当前目录的所有直接子目录? - How can I find all immediate sub-directories of the current directory on Linux? 如何从 Linux 上的单个目录中删除 10 亿个文件? - How to remove one billion files from single directory on linux? 如何在Linux中按用户获取所有文件和目录 - How to get all files and directories by user in Linux
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM