使用 sed 从传入流中删除换行符 [英] removing new line character from incoming stream using sed

查看:50
本文介绍了使用 sed 从传入流中删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 shell 脚本的新手,我正在尝试使用 SED 从每一行中删除换行符.这就是我到目前为止所做的:

I am new to shell scripting and i am trying to remove new line character from each line using SED. this is what i have done so far :

printf "{new
to
linux}" | sed ':a;N;s/
/ /g'

仅删除 Ist 换行符.我在某处找到了这个命令:

removes only Ist new line character. I somewhere found this command :

printf "{new
to
linux}" | sed ':a;N;$!ba;s/
/ /g'

但它给出:ba:找不到事件."

but it gives :"ba: Event not found."

如果我这样做:

printf "{new
to
linux}" | sed ':a;N;s/
/ /g' | sed ':a;N;s/
/ /g'

然后它给出了正确的输出,但我正在寻找更好的东西,因为我不确定当我运行脚本时会得到多少个新角色.传入流来自 echo 或 printf 或脚本中的某个变量.提前致谢

then it gives correct output but i am looking for something better as i am not sure how many new character i will get when i run the script. incoming stream is from echo or printf or some variable in script. Thanks in advance

推荐答案

要删除换行符,请使用 tr:

To remove newlines, use tr:

tr -d '
'

如果你想用一个空格替换每个换行符:

If you want to replace each newline with a single space:

tr '
' ' '

错误 ba: Event not found 来自 csh,是由于 csh 试图匹配历史列表中的 !ba.您可以转义 ! 并编写命令:

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$!ba;s/
/ /g'  # Suitable for csh only!!

但是 sed 是错误的工具,您最好使用更合理地处理带引号的字符串的 shell.也就是停止使用csh,开始使用bash.

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

这篇关于使用 sed 从传入流中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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