如何将多行输出连接到一行? [英] How to concatenate multiple lines of output to one line?

查看:247
本文介绍了如何将多行输出连接到一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行命令 cat file | grep模式,我得到很多输出行。如何将所有行连接成一行,并用\来有效地替换每个\\\
(以后跟空格结束)?



cat file | grep模式| xargs sed s / \ n / / g
不适合我。

解决方案

使用 tr'\ n'''将所有换行符转换为空格:

  $ grep模式文件| tr'\\\
'''

注意: grep 读取文件, cat 连接文件。不要 cat文件| grep



编辑:
$ b

tr 只能处理单个字符的翻译。您可以使用 awk 更改输出记录分隔符,如:

  $ grep模式文件| awk'{print}'ORS =''

这会转变:

  one 
two
three

到:

 一个两三


If I run the command cat file | grep pattern, I get many lines of output. How do you concatenate all lines into one line, effectively replacing each "\n" with "\" " (end with " followed by space)?

cat file | grep pattern | xargs sed s/\n/ /g isn't working for me.

解决方案

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two 
three

to:

one" two" three" 

这篇关于如何将多行输出连接到一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆