GB44444
GB44444

Reputation: 57

Bash script using "while read" to call two different variables from a file

I'd be grateful for your help. I believe I need to use 'while read' to achieve what I am hoping to achieve here. I have looked in the forum for similar questions, but can't find an example where more than one variable is called from another file.

I have file.txt, which has two columns and is ~1000 lines long and looks like this:

1 rs3131962
3 rs12562034
2 rs4040617
8 rs79373928
2 rs11240779

I want to write a script, that for each line of file.txt, will take the variable from column 1 and column 2 and place them in different parts of my command. Now, I know that this syntax is completely wrong, but for illustrative purposes, I want it to look something like:

#!/bin/bash
filename='file.txt'
while read file.txt;
do 
./qctool -g chr"$1"_v3.bgen  -os chr"$1"_"$2".bgen -condition-on "$2"
done

..where $1 and $2 represent the variables in the first and second columns of each line in file.txt.

Essentially, I want it to read line 1 of file.txt and execute:

./qctool -g chr1_v3.bgen  -os chr1_rs3131962.bgen -condition-on rs3131962

And once that's done, to move onto line 2, and execute:

./qctool -g chr3_v3.bgen  -os chr3_rs12562034.bgen -condition-on rs12562034

and so on, for all ~1000 lines in file.txt

Could somebody please help me with the getting the syntax right for getting the variables from column 1 and column 2 separately into my script?

Apologies for the poverty of my attempt - any help warmly appreciated.

Upvotes: 0

Views: 73

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74615

You just need to name your variables in your read command:

#!/bin/bash
filename='file.txt'
while read -r first second
do 
./qctool -g chr"$first"_v3.bgen  -os chr"$first"_"$second".bgen -condition-on "$second"
done < "$filename"

Also, read reads from standard input, so pass the contents of the file over standard input using < "$filename" after done.

By the way, I added the -r switch to read because it does no harm and stops the shell trying to do "clever" things with \s in the input that it reads.

Upvotes: 2

Related Questions