Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 删除特定文件并保留一些_Linux_Bash - Fatal编程技术网

Linux 删除特定文件并保留一些

Linux 删除特定文件并保留一些,linux,bash,Linux,Bash,因此,我有一个包含这些.js和.yml文件的目录,还有一个名为config的文件夹 pogi@gwapo-pah:~$ ls index.cat.js index.bird.js index.dog.js index.monkey.js function.yml config 我想执行一个单行bash命令来执行这些 查找是否存在“index.dog.js”,如果没有,则退出 查找“index.dog.js”是否存在,如果存在,则仅删除 其他*.js文件,并保留index.dog.js、fu

因此,我有一个包含这些.js.yml文件的目录,还有一个名为config的文件夹

pogi@gwapo-pah:~$ ls 

index.cat.js
index.bird.js
index.dog.js
index.monkey.js
function.yml
config
我想执行一个单行bash命令来执行这些

查找是否存在“index.dog.js”,如果没有,则退出

查找“index.dog.js”是否存在,如果存在,则仅删除 其他*.js文件,并保留index.dog.jsfunction.yml和文件夹config

pogi@gwapo-pah:~$ ls 

index.cat.js
index.bird.js
index.dog.js
index.monkey.js
function.yml
config
如果命令成功,则文件夹中的文件应如下所示:

index.dog.js
function.yml
config
到目前为止,我已经尝试过了,但是我无法继续缺少的逻辑

if [ -f index.dog.js ] ; then echo 'exists' ; fi
测试“index.dog.js”是否存在,如果存在,请使用
find
生成所有*.js文件(但不是index.dog.js),然后删除它们

编辑正如约翰·库格曼正确建议的那样,最好避免使用
ls
,因为它可能不一致

[ -f "index.dog.js" ] && \
    find . -type f -not -name "index.dog.js" -name \*.js -exec rm {} +

使用
find
命令的另一种方法:

[ -f "index.dog.js" ] && find . -maxdepth 1 -name \*.js -not -name index.dog.js -delete
在当前目录中查找
命令搜索扩展名为
js
但扩展名为
index.dog.js
的任何文件,并将其删除

如果您不在文件所在的目录中,请用文件夹名替换

shopt -s extglob
[[ -f index.dog.js ]] && rm !(index.dog).js
说明:

test
是一种在不需要
else
的情况下执行
if
的方法,无需所有额外语法

&&
是您在没有狗文件时想要的“短路”(退出)

find
使用多个条件查找文件。在本例中,名称与*.js匹配但不是dog文件的文件

find
然后可以对找到的文件执行命令。
{}
是找到的文件的替代文件。
+
意味着将所有文件名放在一个
rm
命令上,而不是每个文件运行一个命令