Yair B.
Yair B.

Reputation: 332

Redirecting output of a shell script to a program

I have a file named numbers.txt. In the file I have all the numbers from 1 to 1000. And I have a program that inserts 1 to 5 in 200 round.

I tried the following script:

while read p; do
  echo $((p % 5 + 1))
done <numbers.txt

It prints numbers from 1 to 5 in 200, as expected.

Now I need to redirect the output to the input of my program. I tried this:

./my-program < while read p; do
  echo $((p % 5 + 1))
done <numbers.txt 

But it failed an error:

syntax error near unexpected token `do'

How can I run ./my-program with input from the loop?

Upvotes: 0

Views: 46

Answers (3)

Root Bug
Root Bug

Reputation: 26

you can try using for loop like

for i in `cat numbers.txt`; do
   echo $[ $i % 5 + 1 ]
done

Upvotes: 1

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

You can use process substitution in Korn shell, Zsh, or Bash:

./my-program < <(
  while read p; do
    echo $((p % 5 + 1))
  done <numbers.txt
)

Upvotes: 1

Ko Cour
Ko Cour

Reputation: 933

./my-program < ... - this syntax is only for files, in your case you want to use this type of redirection:

while read p; do
  echo $((p % 5 + 1))
done <numbers.txt | ./my-program

Upvotes: 1

Related Questions