Home > front end >  Finding if a.fastq file in a directory exists if not, executing a command in bash
Finding if a.fastq file in a directory exists if not, executing a command in bash

Time:07-02

I want to see if a .fastq file exists in the directory /Sample_140/analysis, and if it does, do nothing, else run samtools bam2fq on all the .bam files in that directory. I have tried

if [ -e ./Sample_/analysis/.fastq ];

then

echo "File exists"

else

samtools bam2fq ".bam" > ".fastq"

cat ".fastq" | grep '^@./1$' -A 3 --no-group-separator > "*_r1".fastq

cat ".fastq" | grep '^@./2$' -A 3 --no-group-separator > "*_r2".fastq

fi

Any help is appreciated.

CodePudding user response:

I don't understand very well the problem. The problem is the cat of output files from samtools or what? In this case, what do you try to do with "grep '^@./1$' -A 3 --no-group-separator" ? Thank you

#!/bin/bash

if [ -f "./Sample_/analysis/.fastq" ]
then
   echo "File exists"
else
   samtools bam2fq ".bam" > ".fastq"
   cat ".fastq" | grep '^@./1$' -A 3 --no-group-separator > "*_r1".fastq
   cat ".fastq" | grep '^@./2$' -A 3 --no-group-separator > "*_r2".fastq
fi

exit 0

CodePudding user response:

If subdirectory analysis is a constant name, you may try so:

#!/bin/bash

SOURCE="."

for DIRECTORY in $(ls "$SOURCE/" | grep "Sample_")
do

    echo "Read directory : " $SOURCE/$DIRECTORY

    if [ -f "$SOURCE/$DIRECTORY/analysis/.fastq" ]
    then
       echo "File exists"
    else
       cd $SOURCE/$DIRECTORY
       samtools bam2fq ".bam" > ".fastq"
       cat ".fastq" | grep '^@./1$' -A 3 --no-group-separator > "*_r1".fastq
       cat ".fastq" | grep '^@./2$' -A 3 --no-group-separator > "*_r2".fastq
    fi

done

exit 0

Else if you search for Sample e analysis you can do thus:

#!/bin/bash

SOURCE="."

for DIRECTORY in $(find $(find $SOURCE -name "*sample_*") -name "analysis")
do

    echo "Read directory : " $SOURCE/$DIRECTORY

    if [ -f "$SOURCE/$DIRECTORY/.fastq" ]
    then
       echo "File exists"
    else
       cd $SOURCE/$DIRECTORY
       samtools bam2fq ".bam" > ".fastq"
       cat ".fastq" | grep '^@./1$' -A 3 --no-group-separator > "*_r1".fastq
       cat ".fastq" | grep '^@./2$' -A 3 --no-group-separator > "*_r2".fastq
    fi

done

exit 0

Thank you

  •  Tags:  
  • bash
  • Related