Pass the output of previous command to next as an argument

argumentscommand linecommand-substitutionoutputpipe

I've a command that outputs data to stdout (command1 -p=aaa -v=bbb -i=4).
The output line can have the following value:

rate (10%) - name: value - 10Kbps

I want to grep that output in order to store that 'rate' (I guess pipe will be useful here).
And finally, I would like that rate to be a value of a parameter on a second command (let's say command2 -t=${rate})

It looks to be tricky on my side; I would like to know better how to use pipes, grep, sed and so on.

I've tried lots of combinations like that one but I'm getting confused of these:

$ command1 -p=aaa -v=bbb -i=4 | grep "rate" 2>&1 command2 -t="rate was "${rate}

Best Answer

You are confusing two very different types of inputs.

  1. Standard input (stdin)
  2. Command line arguments

These are different, and are useful for different purposes. Some commands can take input in both ways, but they typically use them differently. Take for example the wc command:

  1. Passing input by stdin:

    ls | wc -l
    

    This will count the lines in the output of ls

  2. Passing input by command line arguments:

    wc -l $(ls)
    

    This will count lines in the list of files printed by ls

Completely different things.

To answer your question, it sounds like you want to capture the rate from the output of the first command, and then use the rate as a command line argument for the second command. Here's one way to do that:

rate=$(command1 | sed -ne 's/^rate..\([0-9]*\)%.*/\1/p')
command2 -t "rate was $rate"

Explanation of the sed:

  • The s/pattern/replacement/ command is to replace some pattern
  • The pattern means: the line must start with "rate" (^rate) followed by any two character (..), followed by 0 or more digits, followed by a %, followed by the rest of the text (.*)
  • \1 in the replacement means the content of the first expression captured within \(...\), so in this case the digits before the % sign
  • The -n flag of the sed command means to not print lines by default. The p at the end of the s/// command means to print the line if there was a replacement. In short, the command will print something only if there was a match.
Related Question