Thursday, March 31, 2011

Highlight lines in stdout/stderr containing a pattern

So you have lots of log lines flying by on stdout, but some of them are much more important than others. It's not always easy to identify which lines you should be paying attention to. One solution is to grep for patterns and then use color to draw your attention to the important part:


# Show only matching lines from stdout and stderr, with 5 surrounding lines

$ ./verboseProgram |& grep -C5 --color=yes "ERROR"

-or-

# Redirect stdout and stderr to a file while also printing them to screen
$ ./verboseProgram |& tee log
# Then do the same matching post-mortem
$ grep -C5 --color=yes "ERROR" log


Another solution is to highlight the lines matching patterns you care about without discarding everything else. This can be done using the following bash/awk script:

## highlight.sh ##

#!/usr/bin/env bash                                                                                                                          
set -ueo pipefail


pattern=$1
awk '{if(/'$pattern'/){print "\033[1;31m"$0"\033[0m"}else{print}}'
###############

Then you can run your program, keep a log file, and still not miss things as they arrive:
$ ./verboseProgram |& tee log | highlight.sh "ERROR"

If you're not a fan of red, you can pick your favorite color from: http://en.wikipedia.org/wiki/ANSI_escape_code

Thursday, March 17, 2011

The missing operator<< for C++ STL's vector

Ever wanted to print a std::vector to stdout/stderr, but been met with a missing operator compile error? It's annoying and simple to fix. Just define operator<< in a header file. Here's a short example:

#include <iostream>
#include <vector>

template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
  out << "[";
  for(typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); ++it) {
    out << *it;
if(it != v.end()-1) out << ", ";
  }
  out << "]";
  return out;
}

int main() {
  std::vector<int> v;
  v.push_back(1);
  std::cerr << v << std::endl;
}

Wednesday, March 9, 2011

Ubuntu mouse issues

Just in case someone else runs across this issue:
From time to time, the mouse on my Ubuntu box (server 10.04 LTS lucid) running Gnome, the Xserver sometimes decides that the mouse needs to always be moving toward the top, bottom, left, or right of the screen. It appears to to stuck there. You can move it away, but it quickly moves back to the edge of the screen along one of these axes. However, this can be fixed without restarting Xorg:

$ sudo -s
$ modprobe -r usbhid; modprobe usbhid

This just removes and re-enables the kernel module that handles human interaction devices via USB. Don't try to type the modprobe commands as 2 lines -- this likely won't be possible since no USB input devices (read: your keyboard) won't work.