Delete all lines between two lines

In the shell script sh.

Data is given in a text file:

string1  
string2 gibberish  
gibberish  
string3 gibberish  
string4  

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

eventually:

string1  
string3  
string4  
+3
source share
4 answers

you can try this. Anything prior to "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
source

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

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

or sed:

sed '/string3/p; /string2/,/string3/d'
+3
source

sed

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

, 3 2

+1

:

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

, string2 , string3.

0

Source: https://habr.com/ru/post/1729996/


All Articles