繁体   English   中英

Mac 上的 sed:如何为每个范围匹配打印一个新行

[英]sed on mac: how to print a new-line for every range-match

对于范围匹配,想知道如何在匹配的同时打印新行。

例如,如果名为 context.txt 的文件的内容类似于

one
begin
two
three
end
four
begin
five 
six
end
seven

然后,这是我通过以下 sed 命令获得的 output

$ sed -n -e '/begin/,/end/p' content.txt 
begin
two
three
end
begin
five 
six
end

相反,我怎样才能像下面这样得到 output:-

begin
two
three
end

begin
five 
six
end

这可能对你有用:

sed -n -e '/begin/,/end/{/end/G;p;}' file

打印范围beginend和 append end匹配时的保留空间。

请参阅此处了解一种班轮解释。

Pipe output 再次通过sed

 sed -n -e '/begin/,/end/p' content.txt | sed 's/^end$/end\n/'

使用您显示的示例,请尝试以下awk代码。

awk '
/^end$/{
  if(found){
     print val ORS $0 ORS
  }
  found=val=""
}
/^begin$/{
  val=""
  found=1
}
found{
  val=(val?val ORS:"")$0
}
'  Input_file

说明:为上文添加详细说明。

awk '                         ##Starting awk program from here.
/^end$/{                      ##checking condition if line is equal to string end.
  if(found){                  ##Checking if found is NOT NULL.
     print val ORS $0 ORS     ##Then printing val ORS current line ORS here.
  }
  found=val=""                ##Nullifying found and val here.
}
/^begin$/{                    ##Checking condition if line is equal to string begin.
  val=""                      ##Nullifying val here.
  found=1                     ##Setting found to 1 here.
}
found{                        ##Checking if found is NOT NULL.
  val=(val?val ORS:"")$0      ##Then keep adding current line to val variable here.
}
'  Input_file                 ##Mentioning Input_file name here. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM