[英]Concatenate in bash the output of two commands without newline character
What I need:我需要什么:
Suppose I have two commands, A
and B
, each of which returns a single-line string (ie, a string with no newline character, except possibly 1 at the very end).假设我有两个命令
A
和B
,每个命令都返回一个单行字符串(即,一个没有换行符的字符串,除了最后可能是 1 )。 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.我需要一个命令(或管道命令序列)
C
,它将命令A
和B
的输出连接在同一行上,并在它们之间插入 1 个空格字符。
Example of how it should work:它应该如何工作的示例:
For example, suppose the output of command A
is the string between the quotation marks here:例如,假设命令
A
的输出是这里引号之间的字符串:
"The quick"
And suppose the output of command B
is the string between the quotation marks here:并假设命令
B
的输出是此处引号之间的字符串:
"brown fox"
Then I want the output of command(s) C
to be the string between the quotation marks here:然后我希望命令
C
的输出是这里引号之间的字符串:
"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:在试图自己找出
C
,似乎以下管道命令序列应该起作用:
{ echo "The quick" ; echo "brown fox" ; } | xargs -I{} echo {} | sed 's/\n//'
Unfortunately, the output of this command is不幸的是,这个命令的输出是
The quick
brown fox
You can use tr
:您可以使用
tr
:
{ echo "The quick"; echo "brown fox"; } | tr "\n" " "
OR using sed:或使用 sed:
{ echo "The quick"; echo "brown fox"; } | sed ':a;N;s/\n/ /;ba'
The quick brown fox
echo "$(A)" "$(B)"
should work assuming that neither A
nor B
output multiple lines.应该假设
A
和B
都不输出多行。
$ echo "$(echo "The quick")" "$(echo "brown fox")"
The quick brown fox
I'll try to explain the solution with another simple example我将尝试用另一个简单的例子来解释解决方案
We've to concatenate the output of the following command:我们必须连接以下命令的输出:
"pwd" and "ls" “密码”和“ls”
echo "$(pwd)$(ls)";
Output: 2 concatenated strings输出:2个连接的字符串
$ commandA () { echo "The quick"; }
$ commandB () { echo "brown fox"; }
$ x="$(commandA) $(commandB)"
$ echo "$x"
The quick brown fox
$ { echo -n "The quick" ; echo -n " " ; echo "brown fox" ; }
The quick brown fox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.