删除两个字符串之间的所有行 [英] Remove all lines between two strings

查看:65
本文介绍了删除两个字符串之间的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在sh shell脚本中.

In a sh shell script.

在文本文件中提供数据:

Given data in a text file:

string1  
string2 gibberish  
gibberish  
string3 gibberish  
string4  

如何使用awk或sed删除 string2 (包括)和 string3 (不包括 string3 )之间的所有行?

How could you use awk or sed to remove all lines between string2 (inclusive) and string3 (not including string3)?

最后以:

string1  
string3  
string4  

推荐答案

,您可以尝试一下."string2"之前的任何内容都不会被删除.

you can try this. Anything before "string2" will not be deleted.

awk 'BEGIN{f=0}
{
    match($0,"string2")
    if(RSTART){
        print substr($0,1,RSTART-1)
        f=1
        next
    }
    match($0,"string3")
    if(RSTART){
        $0=substr($0,RSTART)
        f=0
    }
}
f==0{print}
' file

输出

$ cat file
string1 blah blah
text before string2 junk
gibberish
gibberis string3 text here
string4

$ ./shell.sh
string1 blah blah
text before
string3 text here
string4

这篇关于删除两个字符串之间的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆