【问题标题】:Script for deleting files whose name do not contain certain phrases?用于删除名称不包含某些短语的文件的脚本?
【发布时间】:2015-12-07 09:12:35
【问题描述】:

如果我有一个文件文件夹,我可以编写什么脚本来删除名称中没有特定短语的文件?

我的文件夹包含

oneApple.zip
twoApples.zip
threeApples.zip
fourApples.zip

我想删除文件名中任何位置不包含“一”或“三”的文件。

执行脚本后,文件夹将只包含:

oneApple.zip
threeApples.zip

【问题讨论】:

    标签: regex bash grep find rm


    【解决方案1】:

    使用 bash

    使用启用extglob 的现代bash,我们可以删除名称不包含onethree 的文件:

    rm !(*one*|*three*)
    

    要试验 extglob 的工作原理,只需使用 echo:

    $ echo !(*one*|*three*)
    fourApples.zip  twoApples.zip
    

    如果上述方法不能正常工作,那么您的 bash 已过期或 extglob 已关闭。开启它:

    shopt -s extglob
    

    使用查找

    find . -maxdepth 1 -type f ! -name '*one*' ! -name '*three*' -delete
    

    在运行该命令之前,您可能需要对其进行测试。只需删除-delete,它就会显示它找到的文件:

    $ find . -maxdepth 1 -type f ! -name '*one*' ! -name '*three*'
    ./twoApples.zip
    ./fourApples.zip
    

    它是如何工作的:

    • .

      这告诉find 查看当前目录。

    • -maxdepth 1

      这告诉find不要递归到子目录

    • -type f

      这告诉find我们只需要常规文件。

    • ! -name '*one*'

      这告诉find 排除名称中带有one 的文件。

    • ! -name '*three*'

      这告诉find 排除名称中带有three 的文件。

    • -delete

      这告诉find 删除它找到的文件。

    【讨论】:

    • 非常感谢!您的 cmets 非常有帮助。
    猜你喜欢
    • 2011-09-27
    • 2016-02-23
    • 2016-06-12
    • 2022-11-10
    • 2023-03-23
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多