我使用的是awk脚本,它删除第一次出现之前和最后一次出现字符串之前和最后一次出现后的所有行--在我的情况下是“讲座”,并在中间删除任何空白行,同时在中间保留任何非讲座行。
Awk脚本
awk '
/Lecture/{
found=1
}
found && NF{
val=(val?val ORS:"")$0
}
END{
if(val){
match(val,/.*Lecture [0-9]+/)
print substr(val,RSTART,RLENGTH)
}
}' 1.txtcat 1.txt
My Dashboard
Fnfjfjf. random test
00:50
1:01:56
My Notes
No data found.
Change Language + English
Submit
Estimation of Working Capital Lecture 1
Estimation of Working Capital Lecture 2
Estimation of Working Capital Lecture 3
Retain this line
Money Market Lecture 254
Money Market Lecture 255
Money Market Lecture 256
International Trade Lecture 257
International Trade Lecture 258
International Trade Lecture 259B Some random text gndgnkdbkdlbkmdbmldbm
Terms And Conditions
84749473837373
Random text fifjfofifofjfkfkf预期输出
Estimation of Working Capital Lecture 1
Estimation of Working Capital Lecture 2
Estimation of Working Capital Lecture 3
Retain this line
Money Market Lecture 254
Money Market Lecture 255
Money Market Lecture 256
International Trade Lecture 257
International Trade Lecture 258
International Trade Lecture 259B Some random text gndgnkdbkdlbkmdbmldbm在现有的脚本中,它工作得很好,但是没有保留最后一次出现字符串“”的行的内容(即以“国际贸易讲座259”而不是“国际贸易讲座259 B”结束)--一些随机文本gndgnkdbkdlbkmdbmldbm。我只希望awk脚本删除所有空白行,删除字符串“讲座”前和最后一次出现后的所有行,同时不更改任何在之间的任何内容,并保留任何非讲座行(否则我只会使用grep )。
发布于 2020-08-17 08:38:40
你能试一下吗。用所示的样品书写和测试。此外,它的OP的现有代码,我已经调整了它的正则表达式,以匹配直到最后出现字符串Lecture
awk '
/Lecture/{
found=1
}
found && NF{
val=(val?val ORS:"")$0
}
END{
if(val){
match(val,/.*Lecture[^\n]*/)
print substr(val,RSTART,RLENGTH)
}
}' Input_file对OP代码改进的解释:,因为OP一直在向名为val的变量中添加行的值。OP的代码没有选择最后一行,所以我将regex改为选择行,直到字符串Lecture的最后一次出现,直到新行出现,以匹配OP提到的最后一行。
发布于 2020-08-18 01:33:19
另一种解决办法是
awk '
/Lecture/ {
seen = 1
print buffer (buffer != "" ? ORS : "") $0
buffer = ""
next
}
seen && NF {
buffer = buffer (buffer != "" ? ORS : "") $0
}
' 1.txt每当读取的行与Lecture匹配时,这将打印出累积的行。
https://stackoverflow.com/questions/63447318
复制相似问题