Ubuntu – Reading lines from a file and storing their content to pass to a C program in a shell script

command linetext processing

I have a C program and the inputs are given through command line. Now I want to pass the inputs from a text file. There are two inputs, a and b, written line by line like this:

a    b
2   423
4    56.9
7   83.5

Now I want to call this txt file in a loop and pass each a and b value line by line so that the output of the C program is generated for each a and b value.

To do so I want to write a shell script which will call the txt file in read mode and after getting the data it will call the C program and then the C program will do the rest including the output.

As I am new to this shell scripting I am confused about how to open a text file and then read data line by line and store them in some variable in the shell script.

Please suggest how can I open the text file in read mode and then read data (which may not be always integers) and store them in some other variables.

Best Answer

Assuming "inputs are given through command line" means that the program accepts command-line arguments, then you should be able to do this with xargs

Ex. given a minimal C program

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("Running %s\n", argv[0]);
  for(int i=1; i<argc; i++) printf("arg %d = %s\n", i, argv[i]);
  printf("\n");
}

compiled with gcc -o someprog someprog.c, and a file of whitespace-separated input arguments inputs.txt

$ cat inputs.txt 
2   423
4    56.9
7   83.5

Then

$ xargs -L1 ./someprog < inputs.txt
Running ./someprog
arg 1 = 2
arg 2 = 423

Running ./someprog
arg 1 = 4
arg 2 = 56.9

Running ./someprog
arg 1 = 7
arg 2 = 83.5

If your input file has a header, you will need to remove it (using tail for example).


If parallel processing would be computationally advantageous for your task, then you could do a similar thing with GNU Parallel

parallel --colsep '[ \t]+' ./someprog {1} {2} :::: inputs.txt