Sunday, March 13, 2022

[SOLVED] How can I put a sed command into a while loop?

Issue

Hoping someone kind can help me pls!

I have an file input.list:

/scratch/user/IFS/IFS001/IFS003.GATK.recal.bam
/scratch/user/IFS/IFS002/IFS002.GATK.recal.bam
/scratch/user/EGS/ZFXHG22/ZFXHG22.GATK.recal.bam

and I want to extract the bit before .GATK.recal.bam - I have found a solution for this:

sed 's/\.GATK\.recal\.bam.*//' input.list | sed 's@.*/@@' 

I now want to incorporate this into a while loop but it's not working... please can someone take a look and guide me where I'm doing wrong. My attempt is below:

while read -r line; do ID=${sed 's/\.GATK\.recal\.bam.*//' $line | sed 's@.*/@@'}; sbatch script.sh $ID; done < input.list

Apologies for the easy Q...


Solution

You can do this in straight up bash (If you're using that shell; ksh93 and zsh will be very similar) no sed required:

while read -r line; do
    id="${line##*/}" # Remove everything up to the last / in the string
    id="${id%.GATK.recal.bam}" # Remove the trailing suffix
    sbatch script.sh "$id"
done < input.list

At the very least you can use a single sed call per line:

id=$(sed -e 's/\.GATK\.recal\.bam$//' -e 's@.*/@@' <<<"$line")

or with plain sh

id=$(printf "%s\n" "$line" | sed -e 's/\.GATK\.recal\.bam$//' -e 's@.*/@@')


Answered By - Shawn
Answer Checked By - Cary Denson (WPSolving Admin)