Use awk to add namespace to C # files
I have several C # classes where the namespace was not added to the file. An example file looks like this (Test.cs):
using System;
using System.IO;
public partial class MyTestClass
{
protected void MyTestVoid()
{
// Magic happens here
}
}
As you can see, there is no namespace declaration. I want the result to be:
using System;
using System.IO;
namespace MyNamespace
{
public partial class MyTestClass
{
protected void MyTestVoid()
{
// Magic happens here
}
}
}
What I am trying to do is write a quick script to insert a namespace around the class definition. I decided to give awk a try, and so I created an awk file like this:
$0 ~ "namespace MyNamespace"
{
foundTrigger = 1;
}
!foundTrigger
{
if ($0 ~ "/^[:space:]*public[:space:]{1}(partial[:space:])*class/")
{
print "namespace MyNamespace\n{\n" $0;
}
else
{
print $0;
}
}
END
{
if (!foundTrigger)
print "}";
}
After doing this for a file (like the one above), it does nothing (other than adding "}" at the bottom of the file).
This is how I understand my regex will be used:
^[:space:]*public[:space:]{1}(partial[:space:])*class
The string must start with zero or more spaces, followed by the word "public", followed by exactly one space, followed by zero or more ("partial" followed by a space), followed by the word "class". Therefore, these lines must match:
public class Test
public partial class Test
And it won't match:
public void Test()
public string Test
However, if I use a regex like this for egrep:
egrep "^[[:space:]]*public[[:space:]]{1}(partial[[:space:]])*class" *.cs
I get this result:
public partial class MyTestClass
Reading the awk man pages shows that:
Regular expressions are an extended look found in egrep.
So I'm not sure why my awk script isn't working. Any help is appreciated. Perhaps there is a better way to accomplish what I am trying to do?
source to share
Maybe it helps to sort out the problem a little. Instead of trying to match the string after / before the regex, try grabbing the entire using
"paragraph". Add to this and complete the file.
BEGIN {
RS = ""; # Read by "paragraphs".
# Records are separated by blank lines.
}
{
if ( NR == 1 )
{
print $0,"\n\nnamespace MyNameSpace;\n{";
RS = "\n";
}
else
{
print "\t", $0; # For indenting
}
}
END {
print "}";
}
Edit: Originally I inserted the "using" directive. He wanted a "namespace" (and corresponding syntax): an almost identical problem. Fixed.
source to share