-2

i need to find a command to delete lines from pattern_1 to the second occurence of pattern_2 (pattern_1 and second occurence of pattern_2 included) with sed.

random_line_1
pattern_1
pattern_2
random_line_3
random_line_4
random_line_5
pattern_2
random_line_6

i need to obtain :

random_line_1
random_line_6

I tried lots of commands inspired by what i have found everywhere but nothing works...

any idea?

mikael
  • 5
  • 1
  • 4
    Welcome to SO, on SO we do encourage users to add their efforts which they have put in order to solve their own problems, so please do add the same in your question and let us know then. – RavinderSingh13 May 27 '20 at 15:46
  • Does this answer your question? [Using sed to delete all lines between two matching patterns](https://stackoverflow.com/questions/6287755/using-sed-to-delete-all-lines-between-two-matching-patterns) – Digvijay S May 28 '20 at 04:24
  • hi Digvijay S thank you for your help, It doesn't answer to my question because i need to match the second occurence of pattern_2. thank you for your help – mikael May 28 '20 at 07:57

1 Answers1

0

Would you please try the following:

sed -n '
/pattern_1/ {                   ;# if the line matches "pattern_1"
    :l1                         ;# then enter a loop for "pattern_2"
    n
    /pattern_2/ {               ;# if the line matches the 1st "pattern_2"
        :l2                     ;# then enter an inner loop for next "pattern_2"
        n
        /pattern_2/ {           ;# if the line matches the 2nd "pattern_2"
            b                   ;# then exit the loop
        }
        b l2                    ;# else jump to "l2"
    }
    b l1
}
p                               ;# print the pattern space
' file
tshiono
  • 21,248
  • 2
  • 14
  • 22
  • Hello, thank you for your help, it works....but in the reverse of what i need. I have replaced the -n by -i at the begining of the command and replaced the p by d at the end in order to delete the content. Finaly, this command delete all the content of the file but not the block i need to delete :-) – mikael May 28 '20 at 07:49
  • @mikael thank you for the feedback. I've tested on several Linux platforms and all of them outputs `random_line_1 random_line_6` as you expect. :-( Can you be specific about your platform and the `sed` version? – tshiono May 28 '20 at 08:18
  • i am on a cygwin plateform with sed v4.2.2, but if i replace -n by -i and p by d the result is the reverse of what i need, but, if i keep your code exactly as you wrote it, and i send the result in a tmp file, it works fine! I have several blocks to delete with this method, i will use tmp file each time i need and it will be perfect! Many thank! – mikael May 28 '20 at 08:30
  • @mikael thank you for prompt testing. Good to know it is working. Note that the `-i` option works along with the `-n` option. So would you please try `sed -ni ...`. Then you will need not to create a tmp file. – tshiono May 28 '20 at 08:48