简体   繁体   English

在Linux中删除几乎所有目录和文件

[英]Removing almost all directories and files in linux

Quick question : I want to delete all but 1 file and 1 directory from the directory I am currently in. How do I do this? 快速问题:我想从当前目录中删除除1个文件和1个目录之外的所有目录。我该怎么做?

The case scenario : 案例场景:

I have a directory which has three directories abc and three files 1.php 2.php 3.php. 我有一个目录,其中包含三个目录abc和三个文件1.php 2.php 3.php。 I want to remove directories a,b and files 1.php and 2.php ONLY! 我只想删除目录a,b和文件1.php和2.php! I am having a hard time trying to do this. 我很难做到这一点。

The solution should scale up, ie I don't want to have to list all the files I do want to delete, only the ones that should stay. 该解决方案应该扩大规模,即我不想列出我确实要删除的所有文件,而只列出那些应该保留的文件。

What do I do? 我该怎么办?

in bash 猛扑

shopt -s extglob
echo rm -r !(3.php|c)

Demo 演示版

$ mkdir -p x/a x/b x/c
$ cd x
$ touch {1,2,3}.php
$ ls -F
1.php  2.php  3.php  a/  b/  c/
$ shopt -s extglob
$ echo rm -r !(3.php|c)
rm -r 1.php 2.php a b

See pattern matching in the bash manual. 请参见bash手册中的模式匹配

Alternatively, 或者,

cd <directory>
rm -r a b [12].php

For deleting all but one file in a general case, it gets more complicated. 在一般情况下,要删除除一个文件外的所有文件,它将变得更加复杂。

Here is a solution in bash (or other shells, I did not check on which ones it works): 这是bash(或其他shell,我没有检查它可以工作的外壳)的解决方案:

function deleteAllBut() {
  local pattern="^($1)"
  for p in "${@:2}"
  do
    pattern="$pattern|($p)"
  done
  pattern=$pattern\$
  for f in *
  do
    [[ $f ~= $pattern ]] || echo $f
  done
}

Then you can call 那你可以打电话

deleteAllBut c 3.php

to list all local files but these two ones. 列出除这两个文件以外的所有本地文件。 (This will not delete hidden files, eg ones whose names start with a . .) (这不会删除隐藏文件,例如名称以.开头的文件。)

How does it work? 它是如何工作的? It first builds a regular expression from the command line arguments (which beforehand were expanded by the shell), then iterates through all files in the current directory and echoes all ones that do not match the pattern. 它首先从命令行参数构建一个正则表达式(该参数事先由shell扩展),然后遍历当前目录中的所有文件,并回显所有与模式不匹配的文件。

Change the echo $f to rm -r $f to actually delete those files and directories. echo $f更改为rm -r $f以实际上删除那些文件和目录。


The following is the original answer for the original question. 以下是原始问题的原始答案。

cd <your directory>
rmdir a b
rm 1.php 2.php

This assumes your directories are empty. 这假设您的目录为空。 If they are not (and you want to remove the contents, too), use 如果不是(并且您也要删除其中的内容),请使用

rm -r a b

instead of the second line above. 而不是上面的第二行。 ( -r stands for recursive .) -r表示递归 。)

Of course, you then can combine the last two lines: 当然,您可以合并最后两行:

rm -r a b 1.php 2.php

or, if you want to be tricky: 或者,如果您想变得棘手:

rm -r a b [12].php

or 要么

rm -r a b {1,2}.php

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM