bash中的for循环通过具有两个特定扩展名的文件 [英] for loop in bash go though files with two specific extensions

查看:101
本文介绍了bash中的for循环通过具有两个特定扩展名的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以下循环遍历m4a文件和webm文件.目前,我使用了两个不同的循环,另一个循环只是替换了该循环中的所有m4a. ffmpeg输出的文件也应该删除m4a扩展名(如果它是m4a文件)和webm扩展名(如果它是webm文件).并将其替换为mp3. (与m4a一样).我不知道该怎么做,我认为它与正则表达式有关,但是我不知道如何真正使用它们,也没有找到一个好的教程/文档,所以如果您有的话,也请链接它

for i in *.m4a ; do
        echo "Converting file $converted / $numfiles : $i"
        ffmpeg -hide_banner -loglevel fatal -i "$i" "./mp3/${i/.m4a}.mp3"
        mv "$i" ./done
        converted=$((converted + 1))
done

解决方案

尝试以下操作:

for i in *.m4a *.webm; do
  echo "Converting file $converted / $numfiles : $i"
  ffmpeg -hide_banner -loglevel fatal -i "$i" "./mp3/${i%.*}.mp3"
  mv "$i" ./done
  converted=$((converted + 1))
done

  • 您可以将for多个模式(全局)一起使用,如此处所示:*.m4a *.webm将扩展为for进行迭代的单个令牌列表.

    • 您可能希望在循环前添加shopt -s nullglob,以便在没有匹配文件的情况下,不使用未展开模式输入它.
  • ${i%.*}.mp3使用参数扩展-具体来说,%用于最短后缀删除-从文件名中删除所有现有扩展名,然后附加.mp3.

请注意,以上技术使用的是模式,而不是正则表达式.虽然关系密切,但存在根本差异;模式更简单,但局限性更大;参见模式匹配.

PS:您可以将converted=$((converted + 1))简化为(( ++converted )).

I want the following loop to go through m4a files AND webm files. At the moment I use two diffrent loops, the other one just replaces all the m4a from this loop. Also the files that ffmpeg outputs should remove a m4a extension if it was a m4a file, and a webm extension if it was a webm file. And replace that with mp3. (As it does here with m4a). I have no Idea how to do it, I think it has something to do with regex expressions, but I have no idea how really use them nor have I ever found a good tutorial/documentation, so if you have one, please link it aswell.

for i in *.m4a ; do
        echo "Converting file $converted / $numfiles : $i"
        ffmpeg -hide_banner -loglevel fatal -i "$i" "./mp3/${i/.m4a}.mp3"
        mv "$i" ./done
        converted=$((converted + 1))
done

解决方案

Try the following:

for i in *.m4a *.webm; do
  echo "Converting file $converted / $numfiles : $i"
  ffmpeg -hide_banner -loglevel fatal -i "$i" "./mp3/${i%.*}.mp3"
  mv "$i" ./done
  converted=$((converted + 1))
done

  • You can use for with multiple patterns (globs), as demonstrated here: *.m4a *.webm will expand to a single list of tokens that for iterates over.

    • You may want to add shopt -s nullglob before the loop so that it isn't entered with the unexpanded patterns in the event that there are no matching files.
  • ${i%.*}.mp3 uses parameter expansion - specifically, % for shortest-suffix removal - to strip any existing extension from the filename, and then appends .mp3.

Note that the techniques above use patterns, not regular expressions. While distantly related, there are fundamental differences; patterns are simpler, but much more limited; see pattern matching.

P.S.: You can simplify converted=$((converted + 1)) to (( ++converted )).

这篇关于bash中的for循环通过具有两个特定扩展名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆