首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在第一次出现之前和最后一次出现特定字符串之前不匹配所有行时保留行的内容?

如何在第一次出现之前和最后一次出现特定字符串之前不匹配所有行时保留行的内容?
EN

Stack Overflow用户
提问于 2020-08-17 08:34:02
回答 2查看 56关注 0票数 0

我使用的是awk脚本,它删除第一次出现之前和最后一次出现字符串之前和最后一次出现后的所有行--在我的情况下是“讲座”,并在中间删除任何空白行,同时在中间保留任何非讲座行。

Awk脚本

代码语言:javascript
复制
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.txt

cat 1.txt

代码语言:javascript
复制
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

预期输出

代码语言:javascript
复制
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 )。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-17 08:38:40

你能试一下吗。用所示的样品书写和测试。此外,它的OP的现有代码,我已经调整了它的正则表达式,以匹配直到最后出现字符串Lecture

代码语言:javascript
复制
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提到的最后一行。

票数 2
EN

Stack Overflow用户

发布于 2020-08-18 01:33:19

另一种解决办法是

代码语言:javascript
复制
awk '
    /Lecture/ {
        seen = 1
        print buffer (buffer != "" ? ORS : "") $0
        buffer = ""
        next
    }
    
    seen && NF {
        buffer = buffer (buffer != "" ? ORS : "") $0
    }
' 1.txt

每当读取的行与Lecture匹配时,这将打印出累积的行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63447318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档