开发者

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?

The case scenario :

I have a directory which has three directories a b c and three files 1.php 2.php 3.php. I want to remove directories a,b and files 1.php and 2.php 开发者_如何学运维ONLY! I am having a hard time trying to do this.

The solution should scale up, i.e. 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.


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):

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, e.g. 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.

Change the echo $f to rm -r $f to actually delete those files and directories.


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.)

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜