Remove all lines between two strings

ぃ、小莉子 提交于 2021-02-07 09:00:35

问题


In a sh shell script.

Given data in a text file:

string1  
string2 gibberish  
gibberish  
string3 gibberish  
string4  

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

to end up with:

string1  
string3  
string4  

回答1:


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

output

$ 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



回答2:


Are string1, string2,string3, etc. each on different lines? In that case, you can use awk:

awk '/string2/{flag=1} /string3/{flag=0} !flag'

or sed:

sed '/string3/p; /string2/,/string3/d'



回答3:


The following will work in sed

sed  '
/string2/,/string3/bdeleting
b
:deleting
s/string3.*/string3/
/string3/b
d
'

presuming we are matching up to the first occurrence of string3 after string2




回答4:


Here's a sample regex substitution:

s/string2.*?(?=string3)//sg

Which will remove everything from string2 up to but not including string3.



来源:https://stackoverflow.com/questions/2136773/remove-all-lines-between-two-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!