Search code examples
awkshechofreebsdxargs

How do I execute a command merging environment variables and variable arguments from a file with xargs?


I have the following file:

%cat temp.csv
2019 11 16
2019 11 17
2019 11 18
2019 11 19
2019 11 20
2019 11 21
2019 11 22
2019 11 23
2019 11 24
2019 11 25
2019 11 26

And I want to execute the following commands:

myvar1="foo"
myvar2="bar"
./test foo 2019 11 16 bar
./test foo 2019 11 17 bar
...
./test foo 2019 11 25 bar
./test foo 2019 11 26 bar

But I do not know how to merge both environment variables and the output of temp.csv easily to pass everything later as arguments to xargs:

cat temp.csv | xargs test $myvar1 -n 3 $myvar2
This does not work!

Solution

  • With GNU xargs:

    xargs -I {} echo ./test "$myvar1" {} "$myvar2" < temp.csv
    

    Output:

    ./test foo 2019 11 16 bar
    ./test foo 2019 11 17 bar
    ./test foo 2019 11 18 bar
    ./test foo 2019 11 19 bar
    ./test foo 2019 11 20 bar
    ./test foo 2019 11 21 bar
    ./test foo 2019 11 22 bar
    ./test foo 2019 11 23 bar
    ./test foo 2019 11 24 bar
    ./test foo 2019 11 25 bar
    ./test foo 2019 11 26 bar
    

    Remove echo if everything looks fine.