使用sed从传入流中删除换行符 [英] removing new line character from incoming stream using 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\nto\nlinux}" | sed ':a;N;s/\n/ /g'
仅删除Ist新行字符。
我在某处找到了此命令:
removes only Ist new line character. I somewhere found this command :
printf "{new\nto\nlinux}" | sed ':a;N;$!ba;s/\n/ /g'
但是它给出了: ba:未找到事件。
but it gives :"ba: Event not found."
如果我这样做:
printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g' | sed ':a;N;s/\n/ /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 '\n'
如果要用单个空格替换每个换行符:
If you want to replace each newline with a single space:
tr '\n' ' '
错误 ba:未找到事件
来自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/\n/ /g' # Suitable for csh only!!
但是sed是错误的工具,最好使用处理引号的外壳字符串更合理。也就是说,停止使用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屋!