Question

say i have a script called myscript and it takes two arguments and should be run as the following:

./myscript 1st 2nd

I also have a text file like this:

213 432
312 54
34 41
1 32

The question is that how can I run myscript using the content of the text file as my input?

The input redirection should result in running exactly the same as the following:

./myscript 213 432
./myscript 312 54
./myscript 34 41
./myscript 1 32

Thank you.

And what if i dont know the number of arguments needed by my script?

Was it helpful?

Solution

You can use while read to read lines from the text file separated with $IFS into two variables and call myscript with it:

while read -r A B; do
    ./myscript "$A" "$B"
done < text_file

To have every line passed as a whole single argument:

while read -r A; do
    ./myscript "$A"
done < text_file

To have each token of every line passed as arguments:

while read -ra A; do
    ./myscript "${A[@]}"
done < text_file

OTHER TIPS

As long as you don't have to preserve any spaces in the arguments, you can manage an indefinite number of arguments using:

while read -r line
do ./myscript $line
done < text_file

If you must preserve spaces, interpret quotes, etc, then the best bet is probably:

sed 's%^%./myscript %' text_file | bash

This inserts the command at the start of each line in the file and then runs the script through bash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top