Linux Command
文章目录

Linux Commands

Rm

Delete all files except the file called important.txt:

1
rm !(important.txt)

In this example, we delete everything except files with the .txt extension.

1
rm !(*.txt)

Remove all files, except those that start with the letter h (case sensitive):

1
rm !(h*)

Delete all files that start with a digit:

1
rm [0-9]*

To Delete all files but exclude those files that start with a digit.

1
rm !([0-9]*)

Delete all files that start with a lowercase a through c

1
rm [a-c]*

If you do not have Bash Extended Globbing enabled, here are some sure fire ways to accomplish the same task.

To learn more about globbing, read our article Standard Wildcards and Globbing Patterns.

Let’s say you have a directory full of files and you want to delete them all except a single file called important.txt. You could use command substitution like this.

1
2
rm -f $(
find . -maxdepth 1 -type f -name "*" ! -name "important.txt")

If you want to delete all files in the current directory and sub-directories and exclude a file from the rm command, you can do something like this.

NOTE: Using -rf will delete files and directories recursively without asking permission. This will destroy all files in the current directory and sub-directories. You should always avoid using -rf if possible.

1
rm -rf $(find . -name "*" ! -name "important.txt")

Another way of accomplishing this is by using find with exec, like this:

1
find . -maxdepth 1 -type f ! -name "important.txt" -exec rm {} \;

扩展: rimraf 的扩展使用

实际上就是 rm

1
2
# 删除目录下所有除了 abc 开头的文件
rimraf . !(abc*)

需要注意一点, [symbolic name] 是一个名字不是一个路径, 因此必须进入到当前目录才能创建当前目录下指向另一个地方的 Symlink

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 创建 Symlink 到一个文件
ln -s [path of the target file/directory] [symbolic name]
ln -s my_folder/my_doc.txt my_document

# 创建 Symlink 到目录
ln -s my_folder my_doc_folder

# Overwrite 一个 Symlink, -sf 代表 force 修改
ln -s my_folder_2/my_doc_2.txt my_document
ln -sf my_folder_2/my_doc_2.txt my_document

# 查看已经创建的 Symlink
ls -l

# 查看 Symlink 的 inode code
ls -i

# 删除 Symlink
unlink [symlink name]

# rm 也可以删除多个 Symlink
rm folder1 folder2 folder2