Issue
I am trying to find files along with the matching password pattern under a given directory on linux using egrep. The pattern found in the files is typically as follows
password=value
pwd=value
pass=value
A file that is matched can contain atleast one of the above patterns for the password anywhere in the file.
There can be one of more spaces or none on either side of the = sign.
The value can either be enclosed in single or double or have no quotes surrounding it.
The value cannot begin with a curly brace { or a single ampersand & or double ampersand &&
Examples of the patterns that should be matched in the files
password = "test123ABc#&$"
pwd=test123ABc#&$
pwd = 'test123ABc#&$'
pass = 'test123456&'
Examples of patterns that should not be matched in the files
password=&testpw
pwd = "{test123@#"
password = "&&test123"
pass={test123@
I currently have this egrep command where i am trying to find the appropriate regex expression to carry out the above task. But the world of regex has just left me confused even though there are resources online. Appreciate any help on this.
egrep -HRi "<regex expression>" <path to directory>
Solution
If PCRE is allowed, which can be enabled using the -P flag in grep.
(password|pwd|pass) *= *+((?=".*")"[^&{][^\s]*"|(?='.*')'[^&{][^\s]*'|(?=[^"'{&].*)[^\s]*)$
Explanation:
(password|pwd|pass) *= *+((?=".*")"[^&{][^\s]*"|(?='.*')'[^&{][^\s]*'|(?=[^"'{&].*)[^\s]*)$
(password|pwd|pass)
matches the literal password phrases specified.*= *+
matches any number of spaces, followed by=
followed by any number of spaces possessively((?=".*")"[^&{][^\s]*"|(?='.*')'[^&{][^\s]*'|(?=[^"'{&].*)[^\s]*)$
(?=".*")"[^&{][^\s]*"
(?=".*")
positive lookahead that looks for any character around"
"[^&{][^\s]*"
matches string not led by&
or{
(?='.*')'[^&{][^\s]*'
(?='.*')
positive lookahead that looks for any character around'
'[^&{][^\s]*'
matches string not led by&
or{
(?=[^"'{&].*)[^\s]*
(?=[^"'{&].*)
positive lookahead that looks if string does not start with"
'
{
&
.[^\s]*
matches rest of string
$
matches end of line
Try it here on https://regex101.com/r/oIEZSS/1
Answered By - Abhishek G Answer Checked By - Candace Johnson (WPSolving Volunteer)