开发者

Remove all lines between two strings

In a sh shell script.

Given data in a text file:

string1  
string2 gibberis开发者_如何学Ch  
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  


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'


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


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


Here's a sample regex substitution:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜