tags:

views:

25

answers:

3

I have a huge collection of videos that all need to be converted into mp4. The folder structure is like this

Events
  Chicago
  Boston
  San Fran
  London Expo

Inside each event holds all of videos in either avi format or .mkv. I want them to be converted to the same file name. but with the mp4 extension.

My question is how do I loop through a folders sub folders, and also keep the file names because at the moment they have spaces in them.. Here is what I have at the moment.

sourcedir="$1"
destdir="$2"
cd "$sourcedir"
for i in `ls`; do
  HandBrakeCLI -i "$i" -o "$destdir/${i%.*}.mp4" --preset="AppleTV"
  echo $i
done

Phillips Code:

cd "$sourcedir"
echo "Directory: $sourcedir"
destdir = sourcedir
for subdir in *
do
  if [[ -d "$subdir" ]]
  then
    for file in "$subdir"/*
    do
      HandBrakeCLI -i "$file" -o "${file%.*}.mp4" --preset=AppleTV
      echo "$file"
    done
  fi
done
+1  A: 

Either use for i in "$sourcedir/*" (or since you've already done a cd there you could do for i in *).

or do find "$sourcedir" -type f | while read -r i (with this, the variable i will include the source directory name, so you'll have to strip that off using a brace expansion or basename).

Dennis Williamson
+1  A: 

Use a nested loop, and don't use ls:

for subdir in "$sourcedir"/*
do
  if [[ -d "$subdir" ]]
  then
    for file in "$subdir"/*
    do
      HandBrakeCLI -i "$file" -o "$destdir/${file%.*}.mp4" --preset=AppleTV
      echo "$file"
    done
  fi
done

Another option is to use find:

find "$sourcedir" -maxdepth 2 -mindepth 2 -type f -exec bash -c 'HandBrakeCLI -i "$0" -o "'"$destdir"'/${0%.*}.mp4" --preset=AppleTV' '{}' ';' -print

Both solutions will work with filenames containing spaces or newlines.

Philipp
Thanks very much it worked perfectly, I had a few corrupted avis!
Josh Crowder
A: 

bash 4

shopt -s globstar
destdir="/somewhere"
for file in **/*.mkv **/*.avi
do
  HandBrakeCLI -i "$file" -o "$destdir/${file%.*}.mp4" --preset=AppleTV
done
ghostdog74