Taiskorgon
Taiskorgon

Reputation: 69

Regular expression for unix config files

For a check if a variable are set or not in a known config file.

I need a regex that matches var=1 but not # var=1. My tries doesn't work. Could me someone help, please?

^(?<!#).*var.* # matches both var=1 and # var=1

EDIT: the follow regex solved the problem in a regex tester (regxlib.com) but grep doesn't find the line grep "^[^#].+(?<=var.*)" ~/testfile.conf

testfile.conf
#var=1 export var=2 export foo=2

Does anybody know why this in grep doesn't work?

EDIT2: The follow expressioon seems to solve my problem.

grep "^[^#]*var" ~/testfile.conf resp.
sed -n "/^[^#]*var/p" ~/testfile.conf

Upvotes: 2

Views: 390

Answers (2)

Matt
Matt

Reputation: 74690

In Perl Compatible Regular Expression, allowing spaces before and between the attribute name, then capturing both the name and the value.

/^\s*([\w]+)\s*=\s*(.+)/

As you have added that you are using grep, PCRE's can be run with grep -P if your grep supports that

The same in basic POSIX regex (that will run in most implementations of grep):

grep "^ *[_[:alnum:]]\+ *= *.\+" config

Upvotes: 0

Emre Acar
Emre Acar

Reputation: 920

This should work for what you specified.

/^[^#].+/gm

If you need "=" too, use this

/^[^#].+=.+/gm

Proof

http://www.regexr.com/3a1jp


EDIT after @mtm, that suggested to avoid pure spaces, so /^[^#]*[^#\s]+\s*=\s*[^#\s]+/gm is another good choice. Remember that truncated declarations, as foo = #123 are also invalid in a config file...

But if you using grep with default regex, the + is not an operator (must be escaped), and generic spaces need to be expressed by [:space:]. Some ways to use a complete regex,

grep "^[^#]*[^#[:space:]]\+[[:space:]]*=[[:space:]]*[^#[:space:]]\+" config
grep -E "^[^#]*[^#[:space:]]+[[:space:]]*=[[:space:]]*[^#[:space:]]+" config
grep -P "^[^#]*[^#\s]+\s*=\s*[^#\s]+" config

more simple and precise is to check the real syntax of your config file, perhaps a@b,1=1 is invalid, so

grep -P "^\s*\w+\s*=\s*[^\s#]+" config

will be simple and a best choice.

Upvotes: 1

Related Questions