Johnathan
Johnathan

Reputation: 1907

How can I pass values from a file to parameters in a shell command?

I am learning how to create scripts in the unix shell. I have a list of genome coordinates that I would like to pass as values to the command line. For example, I have the file Chr1.txt:

Chr1   10    450
Chr1   456   890
...

The shell command is:

maf_parse  --start *value1*   --end *value2*

I would like to iteratively run the shell command with the start ($2) and end ($3) coordinates from Chr1.txt. I have ~1000 entries.

Upvotes: 0

Views: 61

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754010

while read chr1 start end
do
    maf_parse --start "$start" --end "$end"
done < Chr1.txt

Read each line into three variables; run the command. You could use read -r if you wanted to, but it is not necessary with the data you show.

I don't understand the < Chr1.txt at the end. Does it mean "read from"?

It's input redirection, just the same as anywhere else, except it redirects input to the whole while read ...; do ...; done loop. If the program maf_parse might read from standard input, you need to use a different redirection — see the example below.

Moreover, let's say that I have a fourth field ($4) with a name and would like to save each iteration's result in a file with the name; how could I modify your script?

Assuming you have Bash, you can do the read redirection as shown (read -u 3 and 3< Chr1.txt). The rest is neutral between Bourne-like shells.

while read -u 3 chr1 start end file junk
do
    maf_parse --start "$start" --end "$end" > "$file"
done 3< Chr1.txt

The 3's mean use file descriptor 3 instead of 0 (standard input) as the input file descriptor. This leaves the program able to read standard input if it wants to.

Upvotes: 2

Related Questions