Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

regex - for loop in bash go though files with two specific extensions

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 )).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...