Concatenate in bash the output of two commands without newline character
RegexBashSedPipeConcatenationRegex Problem Overview
What I need:
Suppose I have two commands, A
and B
, each of which returns a single-line string (i.e., a string with no newline character, except possibly 1 at the very end). I need a command (or sequence of piped commands) C
that concatenates the output of commands A
and B
on the same line and inserts 1 space character between them.
Example of how it should work:
For example, suppose the output of command A
is the string between the quotation marks here:
"The quick"
And suppose the output of command B
is the string between the quotation marks here:
"brown fox"
Then I want the output of command(s) C
to be the string between the quotation marks here:
"The quick brown fox"
My best attempted solution:
In trying to figure out C
by myself, it seemed that the follow sequence of piped commands should work:
{ echo "The quick" ; echo "brown fox" ; } | xargs -I{} echo {} | sed 's/\n//'
Unfortunately, the output of this command is
The quick
brown fox
Regex Solutions
Solution 1 - Regex
You can use tr
:
{ echo "The quick"; echo "brown fox"; } | tr "\n" " "
OR using sed:
{ echo "The quick"; echo "brown fox"; } | sed ':a;N;s/\n/ /;ba'
###OUTPUT:
The quick brown fox
Solution 2 - Regex
echo "$(A)" "$(B)"
should work assuming that neither A
nor B
output multiple lines.
$ echo "$(echo "The quick")" "$(echo "brown fox")"
The quick brown fox
Solution 3 - Regex
I'll try to explain the solution with another simple example
We've to concatenate the output of the following command:
"pwd" and "ls"
echo "$(pwd)$(ls)";
Output: 2 concatenated strings
Solution 4 - Regex
$ commandA () { echo "The quick"; }
$ commandB () { echo "brown fox"; }
$ x="$(commandA) $(commandB)"
$ echo "$x"
The quick brown fox
Solution 5 - Regex
$ { echo -n "The quick" ; echo -n " " ; echo "brown fox" ; }
The quick brown fox