目录下有好多个文件,且文件名和扩展名都不太一致。我的需求是只想保留yhtz.php这个文件,除此之外的全部删除。

[root@tokyo wwwroot]# cd default/
[root@tokyo default]# ls
index.html  lnmp.gif  ocp.php  p.php  phpinfo.php  phpmyadmin  yhtz.php

方法1:

# 先用ls命令把当前目录下的文件/目录都列出来,然后管道给egrep.
# egrep -v yhtz.php:取反(不包含yhtz.php),然后管道给xargs rm -rf删除
[root@tokyo default]# ls ./ | egrep -v yhtz.php | xargs rm -rf 
[root@tokyo default]# ls
yhtz.php

方法2:

[root@tokyo default]# ls
index.html  lnmp.gif  ocp.php  phpinfo.php  p.php  yhtz.php
[root@tokyo default]# rm -rf !(yhtz.php)
[root@tokyo default]# ls
yhtz.php

方法3:

#!/usr/bin/bash
dirName="/data/wwwroot/test"
filename="yhtz.php"

for i in `ls /data/wwwroot/test`
do
   if [ $i != $filename ];then
      cd $dirName
      rm -rf $i
  fi
done