【问题标题】:Bash loop to remove files matching name structureBash循环删除匹配名称结构的文件
【发布时间】:2018-08-14 20:47:41
【问题描述】:

使用 bash 循环,我想删除文件夹中三种类型的文件名之一

1) L4.mp3

2) L4 withMusic.mp3

3) L4 noIntro withMusic.mp3

这三种类型的文件很多,唯一变化的是L后面的数字

我想: 保留任何名称如 1(原始文件)的文件

保留任何名称如 3(添加音乐并删除简介)的文件

删除所有名称如 2 的文件(添加了音乐但没有介绍)

​​>

最好的方法是什么?

我最初的想法(无论如何都没有编译)是:

for file in *.mp3; do
name=${file%%[.]*};
if name !=  "$*trimmed wMusic.mp3";
then
rm file;
fi
done

但输出是:

-bash: name: command not found

-bash: name: command not found

-bash: name: command not found

-bash: name: command not found

【问题讨论】:

  • Bash 无法编译。曾经。因此,您可能在终端上收到了错误消息,请将其添加到问题中。添加此内容时,请格式化代码部分(使用编辑器中的{ } 图标)。
  • rm *"noIntro withMusic.mp3" ?
  • 使用Python
  • @funky-future 那太好了。我将如何在 Python 中做到这一点?
  • if 语句的语法应该是if [ "$name" == "$somevariable" ]

标签: bash file loops terminal


【解决方案1】:

不确定为什么需要循环,但这里有一些建议:

ls *.mp3 | grep '(1)' | xargs -d"\n" rm

这将获取所有包含表达式 (1) 的 .mp3 文件,例如abc(1).mp3 等

如果您想在您的方法中获得更广泛的影响或更具动态性,我建议您在 grep 中使用正则表达式:

ls *.mp3 | grep -P "regex-here" | xargs -d"\n" rm

如果您想删除一些其他类型的文件,例如mp4 等也可以在同一命令中使用:

ls *.{mp3,mp4,mpeg} | grep -P "regex-here" | xargs -d"\n" rm

您还可以在find的帮助下使用正则表达式和删除:

find -iregex 'regex-here' -delete

【讨论】:

    猜你喜欢
    • 2018-04-14
    • 2021-09-20
    • 2019-11-11
    • 2019-01-27
    • 2021-09-05
    • 1970-01-01
    • 2012-10-05
    • 2014-07-07
    • 2017-01-03
    相关资源
    最近更新 更多