UNIX: How to run a program with a file as an input

后端 未结 2 638
眼角桃花
眼角桃花 2021-01-14 13:16

I\'m writing a bash script called \'run\' that tests programs with pre-defined inputs.

It takes in a file as the first parameter, then a program as a second paramete

相关标签:
2条回答
  • 2021-01-14 13:37

    The < operator redirects the contents of the file to the standard input of the program. This is not the same as using the file's contents for the arguments of the file--which seems to be what you want. For that do

    ./program $(cat file.txt) 
    

    in bash (or in plain old /bin/sh, use

    ./program `cat file.txt`
    

    ).

    This won't manage multiple lines as separate invocations, which your edit indicates is desired. For that you probably going to what some kind scripting language (perl, awk, python...) which makes parsing a file linewise easy.

    0 讨论(0)
  • 2021-01-14 13:43

    A simple test with

    #!/bin/sh
    
    # the whole loop reads $1 line by line
    while read
    do
        # run $2 with the contents of the file that is in the line just read
        xargs < $REPLY $2
    done < $1
    

    works fine. Call that file "run" and run it with

    ./run text.txt ./check
    

    I get the program ./check executed with text.txt as the parameters. Don't forget to chmod +x run to make it executable.

    This is the sample check program that I use:

    #!/bin/sh
    
    echo "This is check with parameters $1 and $2"
    

    Which prints the given parameters.

    My file text.txt is:

    textfile1.txt
    textfile2.txt
    textfile3.txt
    textfile4.txt
    

    and the files textfile1.txt, ... contain one line each for every instance of "check", for example:

    lets go
    

    or

    one two
    

    The output:

    $ ./run text.txt ./check
    This is check with parameters lets and go
    This is check with parameters one and two
    This is check with parameters uno and dos
    This is check with parameters eins and zwei
    
    0 讨论(0)
提交回复
热议问题