regex - awk 连接字符串直到包含子字符串

标签 regex bash awk

我有一个来自 thisawk 脚本示例:

awk '/START/{if (x) print x; x="";}{x=(!x)?$0:x","$0;}END{print x;}' file

这是一个带有行的示例文件:

$ cat file
START
1
2
3
4
5
end
6
7
START
1
2
3
end
5
6
7

因此,当目标字符串包含 end 字时,我需要停止连接,因此所需的输出是:

START,1,2,3,4,5,end
START,1,2,3,end

最佳答案

简短的 Awk 解决方案(虽然它会检查 /end/ 模式两次):

awk '/START/,/end/{ printf "%s%s",$0,(/^end/? ORS:",") }' file

输出:

START,1,2,3,4,5,end
START,1,2,3,end

  • /START/,/end/ - 范围模式

A range pattern is made of two patterns separated by a comma, in the form ‘begpat, endpat’. It is used to match ranges of consecutive input records. The first pattern, begpat, controls where the range begins, while endpat controls where the pattern ends.

  • /^end/? ORS:"," - 为范围内的当前项设置分隔符

关于regex - awk 连接字符串直到包含子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47796211/

相关文章:

regex - 使用 Bash 正则表达式匹配单词边界

linux - 如何按列值分组到行和列标题中,然后对值求和

perl - 合并来自不同文件的列

linux - 在 Bash 脚本中解析命令输出

linux - 使用 AWK/Perl 在 K 列为空时提取行

linux - 脚本的聚合输出

正则表达式 4 个字符和 1 个空格最少的任何位置

javascript - 用引号分割文本而不是javascript中的空格

java - 如何从java中的字符串中提取多个正则表达式匹配

c# - 正则表达式捕获具有 1 到 5 个序数的组