用sed删除几行\ n

时间:2014-08-23 00:48:18

标签: regex sed

我正在尝试使用sed删除两种搜索模式之间的所有换行符。

我首先找到了this post,它教会了我如何在两条线之间进行搜索。

sed -e '/begin/,/end/{s/begin/replacement/p;d}'

然后我找到this post来帮助删除文件中的所有换行符。

sed ':a;N;$!ba;s/\n/ /g'

我试图将这两个答案结合起来并提出:

sed -e '/begin/,/end/{:a;N;$!ba;s/\n/ /p;d}'

然而,它并不是很有效。它从正确的行开始替换换行符,但一直持续到文件末尾。下面给出一个例子:

Sed命令:

sed -e '/Seven/,/Fifteen/{:a;N;$!ba;s/\n/ /g}' input.txt

input.txt中:

One Two Three
Four Five Six
Seven Eight Nine
Ten Eleven Twelve
Thirteen Fourteen Fifteen
Sixteen Seventeen Eighteen
Nineteen Twenty Twenty-One

输出:

One Two Three
Four Five Six
Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen Twenty Twenty-One

我真正想要的是什么:

One Two Three
Four Five Six
Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen
Sixteen Seventeen Eighteen
Nineteen Twenty Twenty-One

感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

您需要将$更改为/Fifteen/

sed -e '/Seven/,/Fifteen/{:a;N;/Fifteen/!ba;s/\n/ /g}' input.txt

  • $!ba =>如果不是最后一行,请跳至a
  • / Fifteen /!ba =>如果不匹配a
  • ,请跳至/Fifteen/

您可以缩短命令:

sed '/Seven/{:a;N;/Fifteen/!ba;s/\n/ /g}' input.txt

答案 1 :(得分:2)

这是awk版本:

awk '/Seven/ && !g {f=1;g=1} /Fifteen/ {f=0} {printf "%s%s",$0,(f?FS:RS)}' file
One Two Three
Four Five Six
Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen
Sixteen Seventeen Eighteen
Nineteen Twenty Twenty-One

这是gnu awk版本(字边界):

awk '/\<Seven\>/ {f=1} /\<Fifteen\>/ {f=0} {printf "%s%s",$0,(f?FS:RS)}' file
One Two Three
Four Five Six
Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen
Sixteen Seventeen Eighteen
Nineteen Twenty Twenty-One

另一个awk版本:

awk '/Seven/ && !/Seven[[:alnum:]]/ && !/[[:alnum:]]Seven/ {f=1} /Fifteen/ {f=0} {printf "%s%s",$0,(f?FS:RS)}' file
One Two Three
Four Five Six
Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen
Sixteen Seventeen Eighteen
Nineteen Twenty Twenty-One

答案 2 :(得分:1)

sed是一个很好的工具,用于单行上的简单替换,但对于其他任何东西(即任何涉及除s,g和p以及-n之外的语言结构的东西)只需使用awk。

将GNU awk用于多字符RS,\<\>字边界以及gensub():

$ gawk -v RS='^$' -v ORS= '{
    match($0,/\<Seven\>.*\<Fifteen\>/)
    print substr($0,1,RSTART-1) \
          gensub(/\n/," ","g",substr($0,RSTART,RLENGTH)) \
          substr($0,RSTART+RLENGTH)
}' file
One Two Three
Four Five Six
Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen
Sixteen Seventeen Eighteen
Nineteen Twenty Twenty-One

毫不夸张 - 所有那些神秘的sed单字符语言结构(N,b,a等)在20世纪70年代中期发明时已经过时了,当时发明了awk并且人们不再需要使用sed进行多行编辑

答案 3 :(得分:0)

您也可以使用此sed方法

sed '/Seven/{:loop ; N ;/\nSixteen/{p;d}; s/\n/ /g; t loop}' filename