Using find - Deleting all files/directories (in L

2019-03-11 04:15发布

If we want to delete all files and directories we use, rm -rf *.

But what if i want all files and directories be deleted at a shot, except one particular file?

Is there any command for that? rm -rf * gives the ease of deletion at one shot, but deletes even my favourite file/directory.

Thanks in advance

标签: linux file shell
11条回答
老娘就宠你
2楼-- · 2019-03-11 04:51

I don't know of such a program, but I have wanted it in the past for some times. The basic syntax would be:

IFS='
' for f in $(except "*.c" "*.h" -- *); do
  printf '%s\n' "$f"
done

The program I have in mind has three modes:

  • exact matching (with the option -e)
  • glob matching (default, like shown in the above example)
  • regex matching (with the option -r)

It takes the patterns to be excluded from the command line, followed by the separator --, followed by the file names. Alternatively, the file names might be read from stdin (if the option -s is given), each on a line.

Such a program should not be hard to write, in either C or the Shell Command Language. And it makes a good excercise for learning the Unix basics. When you do it as a shell program, you have to watch for filenames containing whitespace and other special characters, of course.

查看更多
来,给爷笑一个
3楼-- · 2019-03-11 04:51

you need to use regular expression for this. Write a regular expression which selects all other files except the one you need.

查看更多
女痞
4楼-- · 2019-03-11 04:52
mv subdir/preciousfile  ./
rm -rf subdir
mkdir subdir
mv preciousfile subdir/

This looks tedious, but it is rather safe

  • avoids complex logic
  • never use rm -rf *, its results depend on your current directory (which could be / ;-)
  • never use a globbing *: its expansion is limited by ARGV_MAX.
  • allows you to check the error after each command, and maybe avoid the disaster caused by the next command.
  • avoids nasty problems caused by space or NL in the filenames.
查看更多
The star\"
5楼-- · 2019-03-11 04:54
cd ..
ln trash/useful.file ./
rm -rf trash/*
mv useful.file trash/
查看更多
地球回转人心会变
6楼-- · 2019-03-11 04:58

At least in zsh

rm -rf ^filename

could be an option, if you only want to preserve one single file.

查看更多
登录 后发表回答