Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

regex - 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 (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/
//'

Unfortunately, the output of this command is

The quick
brown fox
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use tr:

{ echo "The quick"; echo "brown fox"; } | tr "
" " "

OR using sed:

{ echo "The quick"; echo "brown fox"; } | sed ':a;N;s/
/ /;ba'

OUTPUT:

The quick brown fox 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...