如题,如何删除LINUX中某个文件夹中选中的文件之外的文件

如题,我的一个文件夹中有如下文件,我要删除文件file1 file2 file3,保留not1和not2这两个文件

[root@VM_0_7_centos test]# ll
total 0
-rw-r--r-- 1 root root 0 Jan 29 11:11 file1
-rw-r--r-- 1 root root 0 Jan 29 11:11 file2
-rw-r--r-- 1 root root 0 Jan 29 11:11 file3
-rw-r--r-- 1 root root 0 Jan 29 11:11 not1
-rw-r--r-- 1 root root 0 Jan 29 11:11 not2

思路一:

直接rm -rf 再利用 !() 方法反选,效率最高。

rm -rf !(not1|not2)

思路二:

利用“反引号(也就是数字键盘1左边那个符号,打出来是这【·】【~】两个符号),把所需要排除的文件特点,比如说not1 和not2的特点就是都有前缀not,给利用grep -v选中,这样做的优势就是每一次删除文件都会有一个系统询问,你可以控制整个过程。

[root@VM_0_7_centos test]# rm `ls | grep -v "not"`
rm: remove regular empty file ‘file1’? y
rm: remove regular empty file ‘file2’? y
rm: remove regular empty file ‘file3’? y
[root@VM_0_7_centos test]# ls
not1  not2

思路三:

利用shopt 反向选择

[root@VM_0_7_centos test]# ls
file1  file2  file3  not1  not2  whatfile4
[root@VM_0_7_centos test]# shopt -s extglob
[root@VM_0_7_centos test]# rm -rf !(not1|not2)
[root@VM_0_7_centos test]# ls
not1  not2
[root@VM_0_7_centos test]# shopt -u extglob

注释:

  • shopt -s extglob 是启动 shopt
  • shopt -u extglob 是关闭 shopt

看似好像和第一条没什么区别,但实际上开启之后,以下5个模式匹配操作符将被识别:

  • ?(pattern-list) – 所给模式匹配0次或1次;
  • *(pattern-list) – 所给模式匹配0次以上包括0次;
  • +(pattern-list) – 所给模式匹配1次以上包括1次;
  • @(pattern-list) – 所给模式仅仅匹配1次;
  • !(pattern-list) – 不匹配括号内的所给模式。

也就是,我们的第一个操作是因为我们已经开启了 shopt,在我们关闭shopt之后,再使用思路一的命令就会报错

[root@VM_0_7_centos test]# rm -rf !(not1)
-bash: !: event not found
[root@VM_0_7_centos test]# ls
shopt命令用于显示和设置shell中的行为选项,通过这些选项以增强shell易用性。
shopt命令若不带任何参数选项,则可以显示所有可以设置的shell操作选项。

思路四:

直接以file名字为目标进行删除,利用正则表达式进行精确定位

rm -rf file[1-3].txt

 

分类: Linux

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注