Re: AWK Code to Strip C comments




pardha.saradhik@xxxxxxxxx wrote:
Hi all,

can any one help me out in writing an awk script that can completely
strip the comments out of a C file.????

i hav tried doing it but unable to strip all comments...

Regards,
Partha

BEGIN { ORS = "" }

{ code = code $0 "\n" }

END {
while ( length(code) )
code = process( code )
}

function process( text )
{
if ( match( text, /"|'|\/\*|\/\// ) )
return span( text )
print text
return ""
}

function span( text , starter )
{
print substr( text, 1, RSTART - 1 )
starter = substr( text, RSTART, RLENGTH )
text = substr( text, RSTART + RLENGTH )

if ( "\"" == starter || "'" == starter )
return quoted( text, starter )
if ( "//" == starter )
return remove( text, "\n", "\n" )
return remove( text, "*/", " " )
}

function remove( text, ender, replacement )
{
print replacement
return substr( text, index(text, ender) + length( ender ) )
}

function quoted( text, starter )
{
if ( "'" == starter )
match( text, /^(\\.|[^'])*'/ )
else
match( text, /^(\\.|[^"])*"/ )
print starter substr( text, 1, RLENGTH )
return substr( text, RSTART + RLENGTH )
}

.



Relevant Pages

  • Re: AWK Code to Strip C comments
    ... i hav tried doing it but unable to strip all comments... ... starter = substr(text, RSTART, RLENGTH) ...
    (comp.lang.awk)
  • Re: Pulling a specific string from a file
    ... I'm looking at pulling a string from a source file and am wondering ... I have a starter and ender quote but am just ... Use strpos to find the position of the starterquote and also for endquote. ... Use substr to retrieve the part inbetween. ...
    (comp.lang.php)