在 bash 中连接两个没有换行符的命令的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20871534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:34:54  来源:igfitidea点击:

Concatenate in bash the output of two commands without newline character

bashsedconcatenationpipe

提问by synaptik

What I need:

我需要的:

Suppose I have two commands, Aand 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) Cthat concatenates the output of commands Aand Bon the same line and inserts 1 space character between them.

假设我有两个命令,AB,每个都返回一个单行字符串(即,一个没有换行符的字符串,除了最后可能是 1)。我需要一个命令(或管道的命令序列)C该串接命令的输出AB在同一行上并插入它们之间的1个空格字符。

Example of how it should work:

它应该如何工作的示例:

For example, suppose the output of command Ais the string betweenthe quotation marks here:

例如,假设 command 的输出A是这里引号之间的字符串:

"The quick"

And suppose the output of command Bis the string betweenthe quotation marks here:

并假设 command 的输出B是此处引号之间的字符串:

"brown fox"

Then I want the output of command(s) Cto be the string betweenthe quotation marks here:

然后我希望命令的输出是这里引号之间C字符串:

"The quick brown fox"

My best attempted solution:

我最好的尝试解决方案:

In trying to figure out Cby 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

回答by anubhava

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'

OUTPUT:

输出:

The quick brown fox 

回答by Mat

echo "$(A)" "$(B)"

should work assuming that neither Anor Boutput multiple lines.

应该工作假设既不A也不B输出多行。

$ echo "$(echo "The quick")" "$(echo "brown fox")"
The quick brown fox

回答by chepner

$ commandA () { echo "The quick"; }
$ commandB () { echo "brown fox"; }
$ x="$(commandA) $(commandB)"
$ echo "$x"
The quick brown fox

回答by hemanto

I'll try to explain the solution with another simple example

我将尝试用另一个简单的例子来解释解决方案

We've to concatenate the output of the following command:
"pwd" and "ls"

我们必须连接以下命令的输出:
“pwd”和“ls”

echo "$(pwd)$(ls)";

Output: 2 concatenated strings

输出:2个连接的字符串

回答by Lirux

$ { echo -n "The quick" ; echo -n " " ; echo "brown fox" ; }
The quick brown fox