Help to replace a blank space with a backslash and blankspace in a variable in Run Shell Command with Automator

automatorbashcompressor

Im creating an automator service that transcodes all the files within a folder to a compressor preset by running the following shell script:

VAR="/Applications/Compressor.app/Contents/MacOS/Compressor -batchname MyFirstBatch"
    for d in "$@"; do
        filename=$(basename "$d")
        fname="$(dirname "$d")"/"${filename%.*}"
        VAR+=" -jobpath "$d" -settingpath /Applications/Compressor.app/Contents/Resources/Settings/ProRes/proResHQName.setting -locationpath "$fname".mov"
    done
eval $VAR

The problem is that the resulting paths in the string have a blank space instead of backslash and blankspace, so I want to replace every " " in the d variable with a "\ ".

Also, is there any way to omit folders and only consider files?

Thank you.

Here's a screenshot of my workflow (Get specified Finder Items and Get folder Contents are just for testing purpose, I disable them when using it as a service):

Screenshot of Automator Service

Best Answer

I don't have Compressor.app to test with, but this should work:

fileargs=()
for d in "$@"
do
    [ -f "$d" ] || continue
    filename=$(basename "$d")
    fname="$(dirname "$d")"/"${filename%.*}"
    fileargs+=(-jobpath "$d" -settingpath /Applications/Compressor.app/Contents/Resources/Settings/ProRes/proResHQName.setting -locationpath "$fname".mov)
done

/Applications/Compressor.app/Contents/MacOS/Compressor -batchname MyFirstBatch "${fileargs[@]}"

EDIT: If you want to restrict it to just specific file extensions (.mov, .mp4, and .mxf), you can use this instead:

fileargs=()
for d in "$@"
do
    [[ "$d" =~ [.](mov|mp4|mxf)$ ]] || continue
    [ -f "$d" ] || continue
    fileargs+=(-jobpath "$d" -settingpath /Applications/Compressor.app/Contents/Resources/Settings/ProRes/proResHQName.setting -locationpath "${d%.*}".mov)
done

/Applications/Compressor.app/Contents/MacOS/Compressor -batchname MyFirstBatch "${fileargs[@]}"

Note that with this restriction, the filename is guaranteed to have an extension, so the ${d%.*}.mov trick that @user3439894 suggested is safe to use. Also, is it ok to use the the same -jobpath and -locationpath names? (This'll happen when both the input and output files are .mov.)