sed:匹配到上一行结尾的模式

sed: matched pattern to end of previous line

我正在尝试将回车 return 替换到上一行的末尾。 ^M是马车return.

示例:

hello 
hello 1^M 
hello 2^M 
hello 3^M
hello 4^M
hello 5^M
hello 6

我需要的:

hello
hello 1 hello 2 hello 3 hello 4 hello 5
hello 6

我希望所有 ^M 都替换到没有 ^M 的上一行的末尾。 你有什么主意吗。如何更换?

这是我的命令:

sed -i 's/^M//g' filtest.txt
sed -i ':a;N;$!ba;s/\n//g' filtest.txt

结果:

hellohello 1hello 2hello 3hello 4hello 5hello 6

感谢您的帮助! :)

这将按照您的意愿执行,使用 GNU awk 进行多字符 RS,并将第三个参数匹配 ():

$ gawk -v RS='^$' -v ORS= '{
    match([=10=],/\r.*\r/,a)
    gsub(/\r(\n|$)/,"",a[0])
    print substr([=10=],1,RSTART-1) a[0] substr([=10=],RSTART+RLENGTH)
}' file
hello 
hello 1hello 2hello 3hello 4hello 5
hello 6