【问题标题】:removing new line character from incoming stream using sed使用 sed 从传入流中删除换行符
【发布时间】:2012-05-24 00:44:38
【问题描述】:

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

printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g'

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

printf "{new\nto\nlinux}" | sed ':a;N;$!ba;s/\n/ /g'

但它给出了:“ba:找不到事件。”

如果我这样做:

printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g' | sed ':a;N;s/\n/ /g'

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

【问题讨论】:

  • “ba:Event not found”错误来自您的 shell。停止使用 csh,或转义 !。
  • @WilliamPursell 我只需要使用 csh,没有其他选项可供我使用。根据您的建议,我放弃了! "printf "{new\nto\nlinux}" | sed ':a;N;$ba;s/\n/ /g'" 这个命令也没有给出正确的结果..我知道使用有很多缺点csh 但由于某些强迫性而不得不使用它:( ..thanks
  • 你不能删除'!',但你需要在它前面加上一个反斜杠。
  • 再次感谢这似乎也有效
  • “在某处找到”很可能是 stackoverflow.com/a/1252191/512360 - 请参阅那里以了解其工作原理。

标签: shell sed csh


【解决方案1】:

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

tr -d '\n'

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

tr '\n' ' '

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

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

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

【讨论】:

  • 感谢您的回复,但您可以使用 tr with 修改来自 echo 或 printf 的传入流吗??
  • 不,这仍然不起作用。即使使用 $\!ba,结果也是来自 csh 脚本的 ba: Event not found
  • 答案应该是sed ':a;N;$\\!ba;s/\n/ /g'
  • 我想替换文件中的一些但不是所有的换行符。例如所有以 PULLUP 结尾的行。这有效:sed ':a;N;$!ba;s/PULLUP\n/ /g;'.
【解决方案2】:

这可能对你有用:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

或:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

或:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

【讨论】:

  • +1:很好地使用粘贴。请注意,由于(错误)引用规则,此处的 sed 解决方案不适用于 csh,并且仍然必须转义 !
  • 耶粘贴。但它最后需要一个破折号,以表明它应该从标准输入读取:paste -sd" " -
  • tr -d "\n" 只给我留下了 stdin.. 的最后一行:/(在 Mac 上)
猜你喜欢
  • 1970-01-01
  • 2018-01-21
  • 2015-02-15
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多