I can't find a regex that will delete a group of lines where the starting and ending lines contain curly braces

Viewed 57

I have many files with lines that begin with main followed by a left curly brace and end with a line containing a right curly brace. I want to remove these lines:

main {
        top:190px;
        margin-left:auto;
        margin-right:auto;
        width:70%
}

I've tried commands like this where I escape the curly braces:

find . -name "*.html" -exec sed -i '/^main.*\{/,/^\}/d' {} +

and gotten error messages like this:

sed: -e expression #1, char 11: Invalid preceding regular expression

When I don't escape the curly braces, I don't get an error message but it doesn't remove the lines.

I'm using GNU sed version 4.7 on a system running GNU bash version 5.0.3(1)-release (x86_64-pc-linux-gnu)

2 Answers

The Invalid preceding regular expression error is caused by the invalid regular expression you used. Since there is no -E flag, your sed command is interpreted with the POSIX BRE regex rules, and \{ / \} are used to define range quantifiers (also, known as limiting or interval quantifiers).

Thus, all you need is either to add -E option,

find . -name "*.html" -exec sed -E -i '/^main.*\{/,/^\}/d' {} +

Or, remove eascapes from { and }:

find . -name "*.html" -exec sed -i '/^main.*{/,/^}/d' {} +

See this online demo.

Of course, if you need to match { only if there are just whitespace chars between main and {, replace /^main.*{/ with /^main[[:space:]]*{/ (POSIX BRE).

You may try that:

^[ \t]*main[ \t]*\{[^{}]+\}$

Demo

Related