-   Linux - Newbie (
-   -   how can I "cat" or "grep" a file to ignore lines starting with "#" ??? (

callagga 07-09-2008 04:56 PM

how can I "cat" or "grep" a file to ignore lines starting with "#" ???

How can I "cat" or "grep" a file to ignore lines starting with "#" ???

That is, to list config files that have more comments "# xxxx" than content often. If I just want to see the file without comments and perhaps blank lines.


matthewg42 07-09-2008 05:00 PM


grep -v '^#' filename

callagga 07-09-2008 05:04 PM

arrr, excellent thanks - if I wanted to ignore blank lines as well do you know what it would be then?

David the H. 07-09-2008 05:09 PM

To provide a little more explanation for the above command, the caret '^' represents the start of a line, so you're testing only for # symbols that appear at the beginning of each line. And the '-v' option in grep inverts the selection, so only lines that don't match get displayed.

I suggest working your way through a simple Regular Expression (regex) tutorial (such as this one) if you really want to know how to harness the power of text matching. It's really worth the effort.

Edit: You can pipe the output through grep again to remove the blank lines. There may be more 'proper' ways to do it, but quick and dirty:

grep -v '^#' filename | grep -v '^$'
The '$' sign matches the end of a line.

callagga 07-09-2008 05:31 PM

thanks - I'd just tried this myself & was pondering a better way to do it

David the H. 07-09-2008 05:45 PM

Actually, thinking about it a bit more, a cleaner way would be to use an 'or' operator so you can include both patterns in a single operation. You need to use switch to egrep though.

egrep -v '(^#|^$)' filename

or alternately

egrep -v '^(#|$)' filename

syg00 07-09-2008 05:58 PM

I always use "egrep -v '(^#|^\s*$)' filename" - especially on Debian derived systems.

kilrogg 08-16-2013 07:58 AM

I tend to use egrep -v '(^#|^\s*$|^\s*\t*#)' filename which also excludes comment lines starting with TAB or SPACE and nothing else before the comment (frequent in config files with multi-line comments behind a setting).

All times are GMT -5. The time now is 06:09 PM.