简体   繁体   English

用于删除名称中不包含某些短语的文件的脚本吗?

[英]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

Using bash 使用bash

With a modern bash with extglob enabled, we can delete files whose names do not contain one or three with: 在启用了extglob的现代bash中,我们可以使用以下命令删除名称不包含onethree的文件:

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

Using find 使用查找

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM