简体   繁体   English

将awk输出管道到C程序

[英]pipe awk output into c program

Hi I have written ac program that takes 3 integers as input: 嗨,我编写了一个ac程序,该程序需要3个整数作为输入:

./myprogram 1 2 3

and I am aiming to pipe data from a csv file into the input of the c program. 我的目标是将数据从csv文件传送到c程序的输入中。 I grab each line from the c program using: 我使用以下命令从c程序中抓取每一行:

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. 然后将其输出通过管道传递到我的c程序中。 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? 如何将输出通过管道传输到c程序​​?

Thanks 谢谢

It helps when you really try to understand error messages the shell gives you: 当您真正尝试理解Shell给出的错误消息时,它会有所帮助:

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 | hello on a clear command line, you'll get the exact same error, because that's the exact same situation as ; | ... 在清晰的命令行上| hello ,您将得到完全相同的错误,因为这与; | ...完全相同; | ... ; | ... ; | ... 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: 您不需要那里的awk ,这同样适用:

     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 ( | ). 在shell中,它不喜欢显式的行终止符,后接管道( | )。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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