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.
stdin
)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:Passing input by
stdin
:This will count the lines in the output of
ls
Passing input by command line arguments:
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:
Explanation of the
sed
:s/pattern/replacement/
command is to replace some pattern^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-n
flag of thesed
command means to not print lines by default. Thep
at the end of thes///
command means to print the line if there was a replacement. In short, the command will print something only if there was a match.