0

I´m trying to batch process a great number of files using bash shell in Mac Terminal. The script is going to mix together 2 versions of the same audio file, that have been processed differently, using SoX Sound Exchange library and the -m (for mix) command. I have been able to combine one simple mix of 2 separate files, like this:

sox −m file1.wav file2.wav mixed.wav

The above works like a charm and just outputs the correct result.

However, while writing the batch processing script, to get all files in the folder to be combined, I run into trouble. First off, my files are named as follows:

af01-sweep1.wav
af01-sweep2.wav
af02-sweep1.wav
af02-sweep2.wav
af03-sweep1.wav
af03-sweep2.wav

… and so forth…

Here is the script:

for file in ./*sweep1*
do
for file2 in ./*sweep2*
   do
       out=COMBINED
       sox -V4 -m -v 1 $file -v 1 $file2 $file-$out.wav
   done
done

What happens as a result of this script is that it combines every file with the token “sweep1” with every file containing “sweep2”. I need to just combine for ex af01-sweep1.wav with af01-sweep2.wav and so forth. I do not know what command or sign to put here to tell bash to look for the same name but with the difference of “sweep1” and “sweep2”. I have thousands of files, so making a script that handles couples is vital.

I´ve read around on bash solutions and found something called -NAME and believe this to be able to be used together with commands like MATCH or FIND. Unsure, as I do not do programming normally.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
AndyE
  • 21
  • 1
  • 4
  • Some of the answers in [Looping over pairs of files](https://stackoverflow.com/questions/28725333/looping-over-pairs-of-values-in-bash) are very relevant, though the question itself isn't quite 100% on-point. Did you try searching for duplicates before asking a new question? – Charles Duffy Sep 25 '17 at 21:14
  • BTW, `$file1` is not the same as `"$file1"`. It might look like it works sometimes, but when you get more interesting filenames (ie. names with spaces or globs), it can fail badly. Use quotes around all expansions; consider running code through http://shellcheck.net/ – Charles Duffy Sep 25 '17 at 21:19

1 Answers1

0
for f1 in *-sweep1.wav; do
  prefix=${f1%-sweep1.wav}
  f2=${prefix}-sweep2.wav
  fout=${prefix}-mixed.wav
  [[ -e $f2 ]]   || { echo "Could not find $f2; skipping $f1" >&2; continue; }
  [[ -e $fout ]] && { echo "$fout already exists; skipping $f1" >&2; continue; }
  sox -V4 -m -v 1 "$f1" -v 1 "$f2" "$fout" 
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • (Community Wiki to avoid harvesting rep from answering a known dupe). – Charles Duffy Sep 25 '17 at 21:17
  • This worked out perfectly for me. I can use any name in front of the "sweep1" and "sweep2", it works every time, with the correct results. Verbose mode in SoX says the formatting is correct and problem free. – AndyE Sep 25 '17 at 23:26