Skip to content
Advertisement

Bash match on any lines that have any number of whitespace up to #

I need to clean up a config file before a source it. I need to remove any lines that have

  • Start with #
  • Any number of white space then a #
  • blank lines
  • Remove (and including) # and everything after it if line starts with a string.

Example config:

# comment
     # comment
dog=woof
cat=meow
moose=huuuuu #comment

# comment
### comment

I have this right now

config_params="$(cat ./config_file.conf | grep -v "^#.* | awk -F '=' '{print$1}')"

The problem is line 2, # comment any number of space up to a #. How can I match to remove lines like this?

Advertisement

Answer

You may use this awk:

awk -F= 'NF == 2 {sub(/[[:blank:]]*#.*/, ""); print}' file

dog=woof
cat=meow
moose=huuuuu

Or if you want to print only key names then use:

awk -F= 'NF == 2 {sub(/[[:blank:]]*#.*/, ""); print $1}' file

dog
cat
moose
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement