Posts Tagged ‘python’

having fun with sed

2008-02-11

I wanted to convert a whole bunch of scripts from a c-like syntax into python scripts. Along came sed…

cat > /tmp/convert.sed <<EOF
# Remove ; at end of line
s/;$//g

# Remove white space in front of lines (python indentation)
s/^[[:space:]]*//g

# Convert // styled comments to #
s+//+#+g

# Comment out /* styled comments */
\/\*/,/\*\// {
  s/^/# /g
}

# if else statements
# Not all statements work correctly yet, e.g.
# statements with "else" inside them (something_else();)
/^[^#]*else/,/}/ {
   s/ *else/else:/
   s/{//
   /else/! { s/}// }
   /else/! { s/^/   / }
}

/^ *if/,/}/ {
  s/if *(\(.*\))/if \1:/
  s/{//
  /if/! { /}/! { s/^/   / } }
  s/}//
}

# pythonify for loops
/^ *for/,/}/ {
   s/for *( *int *\(..*\) *= *\(.*\) *; *\1 *< *\(..*\) *; *\1++ *)/for \1 in range(\2,\3):/
   s/}//
   s/{//
   /for/! {
     s/^/   /
   }
}
EOF

cat > /tmp/example.c <<EOF
// Let's start with something simple
  some_line_with_space_before();

/*
 * here we do something different
 */
if(foo()) {
not_wel_indented_here();
} else {
foo();
}

for(int i = 0; i < 10; i++) {
  more_stuff(i);
}
EOF

sed -f /tmp/convert.sed < /tmp/example.c

It was the first time I needed block statements. It sure is a powerful language.


Design a site like this with WordPress.com
Get started