To index all .bam files only within subdirectories whose names start with a digit (at any depth), you can use the following command in Bash:
bash
find . -type d -name '[0-9]*' -exec find {} -type f -name '*.bam' -exec samtools index {} \; \;
✅ Explanation:
find . -type d -name '[0-9]*'
This finds all directories (at any depth) whose names start with a digit (e.g., 1_data, 2023_samples, results/3_analysis).
-exec find {} -type f -name '*.bam' -exec samtools index {} \; \;
For each such directory ({}), it runs a nested find to locate all .bam files inside it (including subdirectories of that directory) and then indexes them using samtools index.
other_dir/sample4.bam (because other_dir does not start with a digit)
🔍 Alternative: Using -prune (for advanced users)
If you prefer a single find command using -prune (to avoid nested find), you can use:
bash
find . -type d ! $ -name '.' -o -name '[0-9]*' $ -prune -o -type f -name '*.bam' -exec samtools index {} \;
This tells find to prune (skip) any directory that is not the current directory (.) and does not start with a digit.
It then indexes all .bam files found in allowed directories.
⚠️ Note: This version includes files in the current directory (.) if they are .bam. If you want to exclude the current directory and only process subdirectories, add -mindepth 2:
bash
find . -mindepth 2 -type d ! $ -name '.' -o -name '[0-9]*' $ -prune -o -type f -name '*.bam' -exec samtools index {} \;
🛠️ Tips:
Test before running: Replace -exec samtools index {} \; with -print to see which files would be indexed:
bash
find . -type d -name '[0-9]*' -exec find {} -type f -name '*.bam' -print \; \;
Parallel processing: If you have many files and want to speed things up, use xargs with -P:
bash
find . -type d -name '[0-9]*' -exec find {} -type f -name '*.bam' \; | xargs -P 4 -I {} samtools index {}
✅ Summary:
Use the nested find approach for clarity and correctness:
bash
find . -type d -name '[0-9]*' -exec find {} -type f -name '*.bam' -exec samtools index {} \; \;
This ensures only .bam files in subdirectories starting with a digit are indexed, regardless of their depth in the file tree.
Let me know if you need to adapt this for other tools like bamtools or to handle .bai files differently!