Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do foreach *.mp3 file recursively in a bash script?

The following works fine within the current folder, but I would like it to scan sub folders as well.

for file in *.mp3

do

echo $file

done
like image 459
Larry Avatar asked Apr 10 '13 15:04

Larry


1 Answers

There are lots of ways to skin this cat. I would use a call to the find command myself:

for file in $(find . -name '*.mp3') do
  echo $file
  TITLE=$(id3info "$file" | grep '^=== TIT2' | sed -e 's/.*: //g')
  ARTIST=$(id3info "$file" | grep '^=== TPE1' | sed -e 's/.*: //g')
  echo "$ARTIST - $TITLE"
done

If you have spaces in your filenames then it's best to use the -print0 option to find; one possible way is this:

find . -name '*.mp3' -print0 | while read -d $'\0' file
do
  echo $file
  TITLE=$(id3info "$file" | grep '^=== TIT2' | sed -e 's/.*: //g')
  ARTIST=$(id3info "$file" | grep '^=== TPE1' | sed -e 's/.*: //g')
  echo "$ARTIST - $TITLE"
done

alternatively you can save and restore IFS. Thanks to David W.'s comments and, in particular, for pointing out that the while loop version also has the benefit that it will handle very large numbers of files correctly, whereas the first version which expands a $(find) into a for-loop will fail to work at some point as shell expansion has limits.

like image 196
drquicksilver Avatar answered Oct 14 '22 16:10

drquicksilver