linuxfor-loopabsolute-pathbasename

Using basename and absolute path inside a for loop at the same time


Let's say I have

for i in `ls -1 /home/samples/*_1.fq.gz | sed 's/_1.fq.gz//'`
do
bbduk.sh -Xmx1g in1=$i\_1.fq.gz in2=$i\_2.fq.gz out1=/home/output/BASENAME\_clean_1.fq.gz out2=/home/output/BASENAME\_clean_2.fq.gz ref=/home/bbduk/bbmap/resources/adapters.fa ktrim=r k=23 mink=11 hdist=1 tpe tbo qtrim=r trimq=10 maq=10 
done

I'm trying to do so the input (in1 and in2) is the absolute path, which it does with the current code, but then the output (out1 and out2) must be the basename of i

This is because I need the program to output "basename_clean_1.fq.gz" and "basename_clean_2.fq.gz" to a directory that is different from the origin of the files

Any ideas?


Solution

  • Use parameter expansion to manipulate the names. ${i%_1.fq.gz} will remove the suffix from $i, and ${i##*/} gives you the basename. eg:

    for i in /home/samples/*_1.fq.gz; do   
        s="${i%_1.fq.gz}"
        echo basename: "${s##*/}"
        echo fullpath: "$s"
    done