• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 212
  • Last Modified:

Command to Hide Comments

I am often presented with config files modified by someone else and would like to make sure they are correct.
The problem with most config files is that there are only a few lines of active code and often hundreds of lines of comments.

Is there a simple bash command that will cat a file and skip all blank lines and all lines that start with #?

One of my techs wrote a perl script but that seems overkill.

0
davidpm
Asked:
davidpm
  • 6
  • 2
  • 2
  • +2
1 Solution
 
yuzhCommented:
use can use the following command line to do the job:

assume your file name is: yourfile.txt

cat yourfile.txt | grep -v "^#" | grep -v "^$" | more

you can redirect to "less" or another file.
0
 
chris_calabreseCommented:
I'll second that.
0
 
ahoffmannCommented:
# only one process needed:
  awk '($1 ~ /^#/){next}(NF==0){next}{print}' file
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
davidpmAuthor Commented:
Thanks ahoffman but I'm ready for another language just yet.

The following works:
cat test.conf | grep -v "^#" | grep -v "^[[:space:]]*$"

The last grep means match if the line only has zero or more whitespace characters in it. This should match space and tab etc.

That last part is a little hard to remember. Is there a trimmer way of doing the same thing?


0
 
yuzhCommented:
You can define a function in your .profile

eg:

readconf ()
{
cat $1 | | grep -v "^#" | grep -v "^[[:space:]]*$"

}


to use it:

readconf test.conf
0
 
ahoffmannCommented:
FYI,
my suggestion works with any flaviour of awk on any UNIX,
"[[:space]]" is GNU-grep (and derivates) only (well, the default on Linux anyway).
And if performance or resources are in question: only one process ;-)
0
 
DVBCommented:
egrep -v "(^#|^$)" /path/to/file
0
 
ahoffmannCommented:
DVB: s/"/'/g
 and it still does not remove all comment lines
0
 
ahoffmannCommented:
egrep -v '([ \t]*#|^[ \t]*$)' file
0
 
chris_calabreseCommented:
What the heck...

egrep -v '^[ \t]*(#|$)' file
0
 
ahoffmannCommented:
contest closed?
LOL
0
 
ahoffmannCommented:
wow, the longest (characters and cpu time) suggestion got the grade ;-)

davidpm, could you please explain your decision?

(yuzh, no offence)
0
 
DVBCommented:
I think it was the easiest to read. Regular expressions can get complicated.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 6
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now