Home > database >  How to concatenate strings obtained from a .txt document with BASH script?
How to concatenate strings obtained from a .txt document with BASH script?

Time:06-17

I have a txt document that contains a series of arguments that I want to pass to a script. Each argument is on a separate line. I want to make a BASH script that can concatenate these arguments (with white space between each one) and then execute the script with these concatenated arguments. This is the document (d.txt) content:

-format fastq

-in data/test_data.1.fq.gz

-in2 data/test_data.2.fq.gz

-reference hg19

-alignment

-variantcalling

-annotation

-iobio

-out outdir/

-BED

I have tried to do it in the following way but it gives me an error. Instead of concatenating the s

trings, it interprets them as commands. does anybody know how I can fix it?

`

#!/bin/bash

while IFS= read -r line
do
  
  $var=$var$line
  echo $var

done < d.txt

` This is the error I get:

./script.sh: line 6: =-format: order not found

./script.sh: line 6: =-in:order not found

./script.sh: line 6: =-in2: order not found

./script.sh: line 6: =-reference: order not found

./script.sh: line 6: =-alignment: order not found

./script.sh: line 6: =-variantcalling: order not found

./script.sh: line 6: =-annotation: order not found

./script.sh: line 6: =-iobio: order not found

./script.sh: line 6: =-out: order not found

./script.sh: line 6: =-BED: order not found

CodePudding user response:

There is only a little mistake in assigning the Variable.

var=$var$line

instead of

$var=$var$line

CodePudding user response:

You could simplify things a bit by using tr:

$ var=$(tr '\n' ' ' < t.dat)
$ echo "${var}"
-format fastq -in data/test_data.1.fq.gz -in2 data/test_data.2.fq.gz -reference hg19 -alignment -variantcalling -annotation -iobio -out outdir/ -BED 

Your code has some errors with the $var=$var$line, https://shellcheck.net can help with debugging.

Using a loop, per your posted code:

#!/bin/bash

var=""

while IFS= read -r line
do  
  var="${var} ${line}"
done < d.txt

echo "${var}"

Output:

$ ./script 
 -format fastq -in data/test_data.1.fq.gz -in2 data/test_data.2.fq.gz -reference hg19 -alignment -variantcalling -annotation -iobio -out outdir/ -BED
  • Related