简体   繁体   中英

pipe awk output into c program

Hi I have written ac program that takes 3 integers as input:

./myprogram 1 2 3

and I am aiming to pipe data from a csv file into the input of the c program. I grab each line from the c program using:

for i in $(seq 1 `wc -l "test.csv" | awk '{print $1}'`); do sed -n $i'p' "test.csv"; done;

and then would like to pipe the output of this into my c program. I have tried doing:

for i in $(seq 1 `wc -l "test.csv" | awk '{print $1}'`); do sed -n $i'p' "test.csv"; done; | ./myprogram

however I get:

Line 
bash: syntax error near unexpected token `|'

how do I pipe the output into my c program?

Thanks

It helps when you really try to understand error messages the shell gives you:

Line 
bash: syntax error near unexpected token `|'

If you think about it, when you chain commands together in a pipeline, there is never a ; before a | , for example:

ls | wc -l
# and not: ls; | wc -l

Whatever comes after a ; is like an independent new command, as if you typed it on a completely new, clear command line. If you type | hello | hello on a clear command line, you'll get the exact same error, because that's the exact same situation as ; | ... ; | ... ; | ... in your script, for example:

$ | hello
-bash: syntax error near unexpected token `|'

Others already answered this, but I also wanted to urge you to make other improvements in your script:

  1. Always use $() instead of backticks, for example:

     for i in $(seq 1 $(wc -l "test.csv" | awk '{print $1}')); ... 
  2. You didn't need the awk there, this would work just as well:

     for i in $(seq 1 $(wc -l "test.csv")); ... 
  3. You could reduce your entire script to simply this, for the same effect:

     ./myprogram < test.csv 

In the shell, it doesn't like an explicit line termination followed by a pipe ( | ). The pipe already delimits the commands. So you want:

for i in $(seq 1 `wc -l "test.csv" | awk '{print $1}'`); do sed -n $i'p' "test.csv"; done | ./myprogram

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM