xargs with multiple arguments

后端 未结 12 1665
独厮守ぢ
独厮守ぢ 2020-12-13 08:05

I have a source input, input.txt

a.txt
b.txt
c.txt

I want to feed these input into a program as the following:

<         


        
相关标签:
12条回答
  • 2020-12-13 08:39

    dont listen to all of them :) just look at this example:

    echo argument1 argument2 argument3 | xargs -l bash -c 'echo this is first:$0 second:$1 third:$2' | xargs
    

    output will be

    this is first:argument1 second:argument2 third:argument3
    
    0 讨论(0)
  • 2020-12-13 08:40

    How about:

    echo $'a.txt\nb.txt\nc.txt' | xargs -n 3 sh -c '
       echo my-program --file="$1" --file="$2" --file="$3"
    ' argv0
    
    0 讨论(0)
  • 2020-12-13 08:40

    It's simpler if you use two xargs invocations: 1st to transform each line into --file=..., 2nd to actually do the xargs thing ->

    $ cat input.txt | xargs -I@ echo --file=@ | xargs echo my-program
    my-program --file=a.txt --file=b.txt --file=c.txt
    
    0 讨论(0)
  • 2020-12-13 08:44

    Here is a solution using sed for three arguments, but is limited in that it applies the same transform to each argument:

    cat input.txt | sed 's/^/--file=/g' | xargs -n3 my-program
    

    Here's a method that will work for two args, but allows more flexibility:

    cat input.txt | xargs -n 2 | xargs -I{} sh -c 'V="{}"; my-program -file=${V% *} -file=${V#* }'
    
    0 讨论(0)
  • 2020-12-13 08:44

    It's because echo prints a newline. Try something like

    echo my-program `xargs --arg-file input.txt -i echo -n " --file "{}`
    
    0 讨论(0)
  • 2020-12-13 08:46

    Actually, it's relatively easy:

    ... | sed 's/^/--prefix=/g' | xargs echo | xargs -I PARAMS your_cmd PARAMS

    The sed 's/^/--prefix=/g' is optional, in case you need to prefix each param with some --prefix=.

    The xargs echo turns the list of param lines (one param in each line) into a list of params in a single line and the xargs -I PARAMS your_cmd PARAMS allows you to run a command, placing the params where ever you want.

    So cat input.txt | sed 's/^/--file=/g' | xargs echo | xargs -I PARAMS my-program PARAMS does what you need (assuming all lines within input.txt are simple and qualify as a single param value each).

    0 讨论(0)
提交回复
热议问题