This does the job with GNU Sed 4.2.2 at RedHat (you can test it here if you like)
$ sed -n '/class Foo2 {/,/^}$/{s/^}$/Insert here\n\0/};p' file
I assumed that the file could contain more classes , and i try to insert my text (insert here) before the end of class Foo2 in the middle of file.
Testing:
$ cat file2
public class Foo {
// Some code
// There will be functions here, so there are other {}
}
public class Foo2 {
// Some code
// There will be functions here, so there are other {}
}
public class Foo3 {
// Some code
// There will be functions here, so there are other {}
}
$ sed -n '/class Foo2 {/,/^}$/{s/^}$/Insert here\n\0/};p' file2
public class Foo {
// Some code
// There will be functions here, so there are other {}
}
public class Foo2 {
// Some code
// There will be functions here, so there are other {}
Insert here
}
public class Foo3 {
// Some code
// There will be functions here, so there are other {}
}
Explanation:
/class Foo2 {/
, /^}$/
- The range - from class name Foo2 {
up to first ^}$
{s/^}$/Insert here\n\0/}
- The replacement part . Replace ^}$
with your text
plus new line
plus replaced part \0
;p
: Print
Update for BSD
With the fantastic help of @ghoti and after setting up a FreeBSD machine for testing, this seems to work on FreeBSD (bash only):
sed -n "/class Foo2 {/,/^}\$/{s/^}\$/Insert here \\"$'\n'" &/;};p" file
Mind that if shell is not bash, this will not work. You can give a try anyway.