我有一个来自 this 的 awk
脚本示例:
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, whileendpat
controls where the pattern ends.
/^end/? ORS:","
- 为范围内的当前项设置分隔符
关于regex - awk 连接字符串直到包含子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47796211/