I have the following code layout:
#ifndef _file_h_
#define _file_h_
namespace FooBar
{
// code
}
#endif
and I want to run this through sed and convert the FooBar namespace into Foo::Bar and add the closing brace
#ifndef _file_h_
#define _file_h_
namespace Foo { namespace Bar {
// code
}}
#endif
I will admit that my regular expression knowledge is quite poor at the best of times.
I think my command below is somewhere close to achieving what I’m looking for, but I’m getting some of the syntax wrong. Can someone please help?
cat file.h | sed -e 's/(.*)namespace FooBar[\s\n]{(.*)}/\1namesapce Foo \{ namespace Bar \{\2\}\}/g' | less
Knowing that the final brace will always be the last brace in the file gives me an idea that may work:
First, stealing Rob’s first regex:
Next, a new regex for the final brace:
I switched to Perl for the second command so I could use its less-greedy
*?operator, the^and$and\zassertions, and the/msmodifier (to get friendly multi-line matching).These two commands combined made the following changes on your sample file:
This is pretty brittle — a full C++ language parser would be far more robust, though certainly not this easy to write. I hope whatever is left over is easy enough to deal with by hand.