[英]Script for deleting files whose name do not contain certain phrases?
If I had a folder of files, what script could I write to remove the files whose names don't have certain phrases? 如果我有一个文件文件夹,我可以编写什么脚本来删除名称中没有特定短语的文件?
My folder contains 我的文件夹包含
oneApple.zip
twoApples.zip
threeApples.zip
fourApples.zip
I would want to remove the files whose names don't contain "one" or "three" anywhere within their filename. 我想删除名称在文件名中任何地方都不包含“一个”或“三个”的文件。
After executing the script, the folder would only contain: 执行脚本后,该文件夹将仅包含:
oneApple.zip
threeApples.zip
With a modern bash with extglob
enabled, we can delete files whose names do not contain one
or three
with: 在启用了
extglob
的现代bash中,我们可以使用以下命令删除名称不包含one
或three
的文件:
rm !(*one*|*three*)
To experiment with how extglobs work, just use echo: 要试验extglobs的工作方式,只需使用echo:
$ echo !(*one*|*three*)
fourApples.zip twoApples.zip
If the above doesn't work properly, then either your bash is out of date or extglob is turned off. 如果以上操作均无法正常进行,则说明您的bash已过期或extglob已关闭。 To turn it on:
打开它:
shopt -s extglob
find . -maxdepth 1 -type f ! -name '*one*' ! -name '*three*' -delete
Before running that command, you probably want to test it. 在运行该命令之前,您可能需要对其进行测试。 Just remove the
-delete
and it will show you the files that it found: 只需删除
-delete
,它将显示找到的文件:
$ find . -maxdepth 1 -type f ! -name '*one*' ! -name '*three*'
./twoApples.zip
./fourApples.zip
How it works: 这个怎么运作:
.
This tells find
to look in the current directory. 这告诉
find
查找当前目录。
-maxdepth 1
This tells find
not to recurse into subdirectories 这告诉
find
不要递归到子目录
-type f
This tells find
that we only want regular files. 这表明
find
我们只需要常规文件。
! -name '*one*'
This tells find
to exclude files with one
in their name. 这告诉
find
排除名称中只有one
文件。
! -name '*three*'
This tells find
to exclude files with three
in their name. 这告诉
find
排除名称中包含three
文件。
-delete
This tells find
to delete the files that it found. 这告诉
find
删除find
的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.