Friday, September 7, 2007

Displaying uncommented and non-blank lines

If your file is too long with lot of blank and commented lines, this might be the thing you have been looking for: Displaying uncommented and non-blank lines.
Let me explain this with an example of a file that contains a few typical lines from xorg.conf. I call this file neat_file and in my case it looks like this.

Section "ServerLayout"
Identifier "Default Layout"
Screen "Default Screen"
InputDevice "Generic Keyboard"
InputDevice "Configured Mouse"
#InputDevice "stylus" "SendCoreEvents"
#InputDevice "cursor" "SendCoreEvents"
#InputDevice "eraser" "SendCoreEvents"

Section "DRI"
Mode 0666

Let me dissect this problem in portions to ensure that you understand this properly.

$ grep -v '^$' neat_file
^ denotes the beginning of the line and $ denotes the end of the line. So, '^$' denotes blank lines. -v option inverts the selection. Hence, what we get is the non-blank lines. With this half the task is done.

$ grep -v '^#' neat_file
This command is similar to one above except the fact that it looks for lines starting with #. Alas! it doesn't work. It is because in our case the commented lines begin with blank space not #. So, what is the solution?

$ grep -v ^' *#' neat_file
* represents zero or more occurrences. Since, * is preceded by blank space and followed by a #, it will look for zero or more occurrences of blank space followed by a #. And, as usual -v will invert the selection and give those lines which do not match this pattern that is uncommented lines.

Now, how to combine these commands to get desired result?

$ grep -v '^$' neat_file |grep -v ^' *#'
| combines different commands.

Was that useful? Do, comment.

No comments: