0

I would like to obtain a .txt file of the following format:

chr1: 3
chr2: 3
chr3: 3

I use the following script but give different errors:

#!/bin/bash
touch number_samples.txt
for i in {10..22}
do
    a="chr$i:"
    b='\t' 
    c=3
    d='\n' 
    e="$a$b$c$d"
    echo $e > number_samples.txt
done

Note: c=3 would be the output of a tool, i.e. c= tool query -l input.txt | wc -l , so it's a number (the number of words)

How can I do that ?

2

You can use command substitution to substitute the output of a command.

Something like:

c=$(tool query -l input.txt | wc -l)

However your current code is overwriting the file on every iteration of the loop since you are using >. In order to append to the file you should use >>.

Additionally your variables all seem unnecessary, and there is no real reason to touch the file first. You should be able to accomplish this with:

#!/bin/bash
for i in {10..22}
do
    printf '%s\t%s\n' "chr${i}:" "$(tool query -l input.txt | wc -l)" >> number_samples.txt
done

Or if you want to ensure the file is filled with only the data from this loop and any potentially existing data is wiped, you can just write the loop output to file with:

#!/bin/bash
for i in {10..22}
do
    printf '%s\t%s\n' "chr${i}:" "$(tool query -l input.txt | wc -l)" 
done > number_samples.txt

Although the output of tool query -l input.txt | wc -l is going to be the same for each iteration so I'm not sure if you intend to have something changing input.txt on each iteration?

As Steeldriver suggests, if c is not intended to change you could accomplish this without requiring a loop:

c=$(tool query -l input.txt | wc -l)
printf "chr%d\t$c\n" {10..22} > number_samples.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.