FORUMCategory: Generalfinding BAM files with ls and xargs
rcorbett Staff asked 3 years ago



Hi all,
I have a list of libraries in libs.txt and I know the bam files are in /path/to/bamFiles/ but I don’t know the name of the folder each bam file is in.
When looking for just one BAM by library name I can run this:

ls  /path/to/bamFiles/*/myLib*bam

but when I try to loop over a list of libraries I get “no such file or directory” errors:

cat libs.txt | xargs -i ls /path/to/bamFiles/*/{}*.bam

ls: cannot access /path/to/bamFiles/*/oneLib*bam: No such file or directory

3 Answers
rcorbett Staff answered 3 years ago



It turns out that I can get around the error above by calling a new shell command within the xargs command:

cat libs.txt | xargs -i sh -c "ls /path/to/bamFiles/*/{}*.bam"
jrosner Staff answered 3 years ago



Another method would be to pipe the output from the libraries file into a loop, then search for it using the find command, like so:

cat mylibs.txt | while read lib; do find bams/ -name "${lib}*bam"

This would also have the benefit of not producing ‘cannot find’ messages for those folders where a match doesn’t exist.

MarkHahn answered 3 years ago



running multiple finds is crazy inefficient.  why not simply find all the bams and filter the ones you want?  ie:
find /path/to/bamFiles -type f -name \*.bam | fgrep -f libs.txt