Is there an easy way to concatenate the result of two Linux commands, in one line (i.e., without using variables)?

I pull the local outdoor temperature from a nearby weather station. The result today is:

5.2

I simply want to add the units, so the result should look like this:

5.2°C

An example command, that almost gives me what I want is:

wget -q -O- "http://meteocentre.com/montreal/home_e.html" | grep -oP '(?<=Tn= ).*(?=&deg)' ; printf "°C\n"
up vote 9 down vote accepted

Or do it inside-out:

printf "%s°C\n" "$(wget -q -O- "http://meteocentre.com/montreal/home_e.html" | grep -oP '(?<=Tn= ).*(?=&deg)')"

So that the results from wget...|grep... are collected as a command-substitution and inserted into the %s in the printf.

echo, for example, just prints all the arguments you give it. You can use command substitution to turn the output of a command into a string.

echo $(wget -q -O- "http://meteocentre.com/montreal/home_e.html" | grep -oP '(?<=Tn= ).*(?=&deg)') °C

Delete the carriage return at the end of wget’s output:

wget -q -O- "http://meteocentre.com/montreal/home_e.html" | grep -oP '(?<=Tn= ).*(?=&deg)' | tr -d '\n' ; printf "°C\n"
  • 1
    I might have used sed -e s/$/°C/` to append characters at the end of a line and side-step the separate-command concatenation problem entirely. The grep can potentially be folded into the sed -n, too, if you can do what's necessary without PCREs. – Peter Cordes Oct 17 at 2:36

Single sed

As suggested by Stephen Kitt, although this isn't an exact answer to the question...

$ wget -q -O- "http://meteocentre.com/montreal/home_e.html" | sed -n 's/.*Tn= \(.*\)&deg.*/\1°C/p'
3.8°C

\1 is a backref to what is matched inside the parentheses

See this answer for explanation on what the combination of -n and /p does.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.