Archive for February, 2008

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.

smiley in bash prompt

2008-02-07

After the geekdinner of last Tuesday, I couldn’t resist creating my own blog.

As an appetizer, I’ll start with some code snippets I’ve found very usefull. For example the part of my .bashrc which configures the prompt:

smiley() {
    ret_val=$?
    if [ "$ret_val" = "0" ]
    then
        echo ":)"
    else
        echo ":( ($ret_val)"
    fi
}
Green="\033[0;32m"
Yellow="\033[1;33m"
Normal="\033[0m"
PS1="\[$Yellow\]\u@\h\[$Normal\]:\[$Green\]\w \$(smiley) \[$Normal\]"

I always use this because:

  • the coloring makes it easy to see where my previous command started
  • the smiley quickly shows me if and how the previous program exited