Thursday, July 17, 2008

How to remove comments and blank lines from file

So often you need to remove comments and blank lines form configuration files.
You can do it in a very easy single step.

#grep -v ^$ file.conf | grep -v ^#

What it does is grep ^$ from your file. You must be saying I don't have any such character in my file. Actually those characters have their own meaning.

^ begging of the line
$ end of the line

So searching for ^$ means you are searching a blank line.
The -v option invert your search.
So #grep -v ^$ matches all the lines except the blank lines.

Again the pipe '|' sends those match to another grep command which matches any line begging with '#'. Then -v option again inverts the match giving you all the lines except comment and blank lines.

If you want the output in a file rather than screen then redirect it,
#grep -v ^$ file.conf | grep -v ^# > newfile

For more of the input/output and error redirection visit http://techspalace.blogspot.com/2008/06/devnull-2.html

No comments:

Post a Comment