This doesn't seem to work

The next example would delete everything between "ONE" and "TWO:" 

sed '
/ONE/ {
# append a line
# search for TWO on the second line 
    /\n.*TWO/ {
# found it - now edit making one line
        s/ONE.*\n.*TWO/ONE TWO/
}' file

i was expecting to delete everything between ONE and TWO.i tried with file where file contains.

[user5@mailserver ~]$ cat file

but the output come like

[user5@mailserver ~]$ ./test

I was expecting ONE TWO I am trying to make it correct but not able to do.

  • I'd simply use a small PCRE, with by replacing s/ONE.*TWO/ONE\nTWO/n something like this. make sure your Regexp matches around newlines! Here's an answer that'll probably solve your problem: stackoverflow.com/questions/8624283/… – polemon Aug 27 '13 at 12:44

This will do the job

sed '/^ONE/,/TWO/{/^ONE/!{/TWO/!d}}' file

/^ONE/,/TWO/ Look at the first line starting with ONE up to TWO

{/^ONE/! do the following if my line does not start with ONE

{/TWO/!d}} do the following if my line does not start with TWO and delete

To summerize the above:

Find everything that starts with ONE up to TWO. Another check is ran which means, find everything that don't match 'ONEandTWO` and delete the rest.


I would use

sed 'N;N;s/ONE.*\n.*TWO/ONE TWO/' file

Note the two N operations to join three lines together to allow the s opertation to work.

(this also keeps close to your original example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.