如何将换行插入sed行串联中



我有这个代码片段:

cat testfeed.txt | sed '${H;z;x;s/n//g;p;};/0$/!{H;d;};/0$/{H;z;x;s/r//g;}'

它接受我所有的输入并创建一个长记录。我想要的是将记录一与记录二连接起来

因此:

1.
My first line
2.
My Second line

变为:

1. My First line
2. My Second line

代替:

1. My First line. 2. My Second line

我觉得我应该能够插入换行符,但我对sed的了解充其量是很差的:(

如有任何协助,我们将不胜感激。

如果您愿意接受awk解决方案,您可以将其作为

awk 'NF{getline empty;getline line;printf("%s %sn",$0,line)}' input-file
1. My first line
2. My Second line

而你的input-file

$ cat input-file
1.
My first line
2.
My Second line

逻辑非常简单。

  • NF{..旨在确保以下操作仅适用于非空行
  • getline empty;getline line;获取行和行+1并存储在awk变量中,printf相应地打印该变量

如果您想在每行之后添加一个新行,只需在printf中添加另一个"\n"作为printf("%s %snn",$0,line)

awk 'NF{getline empty;getline line;printf("%s %snn",$0,line)}' input-file
1. My first line
2. My Second line
$ cat testfeed.txt 
1.
My first line
2.
My Second line

GNU sed

$ sed 'N;N; s/ns*n/ /; N' testfeed.txt 
1. My first line
2. My Second line
  • N;N;再得到两条线,所以总共有三条线
  • 从这三行中的s/ns*n/ /,将ns*n的第一个出现替换为一个空格。。。例如,这将匹配包含1.的行的末尾和后面的空行(可以包含s个字符,如果该行没有s个字符,则可以删除(
  • 最后一个; N将获得一行,因此下一个匹配将从包含2.的行开始

最新更新