如何在Mac终端用Sox批量修剪子文件夹中的音频文件?
Batch Process Subfolders with WAV & TXT Files
Got it, let's modify your script to automatically traverse all your subfolders and process each pair of .wav and .txt files. Here's a robust version that handles each directory safely:
#!/bin/bash # Enable nullglob to handle cases where no files match (avoids errors) shopt -s nullglob # Traverse every subdirectory in the current folder for dir in */; do # Skip if it's not a directory (just in case) if [ ! -d "$dir" ]; then continue fi echo "Processing directory: $dir" cd "$dir" || { echo "Failed to enter $dir, skipping..."; continue; } # Find the WAV and TXT files in the current directory wav_files=(*.wav) txt_files=(*.txt) # Check if we have exactly one WAV and one TXT file if [ "${#wav_files[@]}" -ne 1 ]; then echo "⚠️ Found ${#wav_files[@]} WAV files in $dir (expected 1), skipping..." cd .. continue fi if [ "${#txt_files[@]}" -ne 1 ]; then echo "⚠️ Found ${#txt_files[@]} TXT files in $dir (expected 1), skipping..." cd .. continue fi wav_file="${wav_files[0]}" txt_file="${txt_files[0]}" echo "Using file pair: $wav_file & $txt_file" # Your original trimming logic, adjusted for the current directory's files index=0 start="" while read -r this; do # Skip empty lines in the TXT file [[ -z "$this" ]] && continue if [ "$index" -gt 0 ]; then # Calculate duration: end time minus start time duration=$(echo "$this - $start" | bc) # Trim the WAV file using sox sox "$wav_file" "clip-$index.wav" trim "$start" "$duration" echo "Created clip: clip-$index.wav (from $start to $this, duration $duration)" fi ((index+=1)) start="$this" done < "$txt_file" # Go back to the parent directory to process the next subfolder cd .. done echo "✅ All processing complete!"
Key Improvements & Notes:
- Directory Traversal: Uses a
forloop to iterate over every subdirectory (*/) in your current working folder. - Error Handling: Checks for exactly one WAV and one TXT file per folder, skips directories with missing/multiple files and prints warnings.
- Robust File Matching: Uses array variables (
wav_files,txt_files) withnullglobenabled to safely handle missing files without throwing errors. - Adjusted Trimming Logic: Replaces hardcoded
sound.wavandtimes.txtwith the actual files found in each subdirectory. Also usesbcto calculate duration explicitly (more reliable than$this-$startin some cases). - User Feedback: Prints status messages so you can track which directory is being processed and which clips are created.
Before Running:
- Make sure
soxandbcare installed on your system (most Linux distros have them by default; on macOS you can install via Homebrew:brew install sox bc). - Test the script on a small subset of your folders first to make sure it works as expected.
- Ensure you have write permissions in each subfolder (to create the clipped audio files).
内容的提问来源于stack exchange,提问作者Bruce Wang
相关产品推荐
相关产品推荐

