LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how can I "cat" or "grep" a file to ignore lines starting with "#" ??? (https://www.linuxquestions.org/questions/linux-newbie-8/how-can-i-cat-or-grep-a-file-to-ignore-lines-starting-with-654683/)

callagga 07-09-2008 03:56 PM

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

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.

Cheers

matthewg42 07-09-2008 04:00 PM

Code:

grep -v '^#' filename

callagga 07-09-2008 04: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 04: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:
Code:

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

callagga 07-09-2008 04:31 PM

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

David the H. 07-09-2008 04: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.
Code:

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

or alternately

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


syg00 07-09-2008 04:58 PM

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

kilrogg 08-16-2013 06: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 03:51 PM.