gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:01:39 25 4
gpt4 key购买 nike

我有一个来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com