【发布时间】:2015-12-07 09:12:35
【问题描述】:
如果我有一个文件文件夹,我可以编写什么脚本来删除名称中没有特定短语的文件?
我的文件夹包含
oneApple.zip
twoApples.zip
threeApples.zip
fourApples.zip
我想删除文件名中任何位置不包含“一”或“三”的文件。
执行脚本后,文件夹将只包含:
oneApple.zip
threeApples.zip
【问题讨论】:
如果我有一个文件文件夹,我可以编写什么脚本来删除名称中没有特定短语的文件?
我的文件夹包含
oneApple.zip
twoApples.zip
threeApples.zip
fourApples.zip
我想删除文件名中任何位置不包含“一”或“三”的文件。
执行脚本后,文件夹将只包含:
oneApple.zip
threeApples.zip
【问题讨论】:
使用启用extglob 的现代bash,我们可以删除名称不包含one 或three 的文件:
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 删除它找到的文件。
【讨论】: