SumitPaliwal SumitPaliwal - 1 month ago 13
Bash Question

Passing filename prefixes to a program as input

I have some files with the following names:

A-C-F3_accepted_hits.bam
A-VR-M6R_accepted_hits.bam


The files are stored on a Linux server. I would like to extract the string before the underscore (i.e.
A-C-F3
,
A-VR-M6R
etc.) from all the files with
.bam
extension.

Subsequently, I would like to use these strings as prefixes for output files generated by another program that will use the
*_accepted_hits.bam
files for input.

To be more specific, my input is as follows:

samtools sort -n A-C-F3_accepted_hits.bam A-C-F3_sorted
samtools sort -n A-VR-M6R_accepted_hits.bam A-VR-M6R_sorted


Here the samtools will sort the contents of A-C-F3_accepted_hits.bam. I want the output file with prefix A-C-F3_sorted followed by default extension. Likewise I have 17 files on which I want to perform this task. Hope this makes things clear.
Thanks.

Answer

You can use awk to extract the prefix of filename and append it to the common part of filename.

OCOMM=_accepted_hits.bam
for i in `ls *.bam`;
    do
            OFILE=`echo $i | awk -F_ '{print $1}'`;
            FILENAME=$OFILE$OCOMM;
            echo $FILENAME;
    done
Comments