lecb
lecb

Reputation: 409

How can I put a sed command into a while loop?

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...

Upvotes: 1

Views: 102

Answers (2)

hek2mgl
hek2mgl

Reputation: 158050

You can use the output of the sed command as input for the loop:

sed 'COMMAND' input.file | while read -r id ; do
    some_command "${id}"
done

Instead of the loop, also xargs could be used:

sed 'COMMAND' input.file | xargs -n1 some_command

ps: GNU sed supports to execute the result of a s operation as a command. I wouldn't recommend to use this in production, for portability reasons at least, but it's worth mention probably:

sed 's/\(.*\)\.GATK\.recal\.bam.*/sbatch script.sh \1/e' input.file

Upvotes: 2

Shawn
Shawn

Reputation: 52439

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@.*/@@')

Upvotes: 0

Related Questions