# grep a certain pattern in a line in a file and output the line if match found in the same line

I have a file lets say temp.log with the following contents-

blahblah SomeOtherClassName blahblahblah
blahblah MyClassName blah blah blah userId:[6729223726254951za],key:[09809890980980908d0e6],token:[0238234234-3948-4d9],SessionScope:[0238234234-3948-4d9],PageScope:[0238234234-3948-4d9],RequestScope:[0238234234-3948-4d9], requestUrl:/blah/blah/blah
blahblah SomeOtherClassName blahblahblah
blahblah MyClassName blah blah blah userId:[6729223726254951za],key:[09809890980980908d0e6],token:[0238234234-3948-4d9],SessionScope:[1111111-3948-4d9],PageScope:[0238234234-3948-4d9],RequestScope:[0238234234-3948-4d9], requestUrl:/blah/blah/blah


I want to parse the log file and output if the log line which have MyClassName and if one of the sessionscope, pagescope or requestscope value does not match the token value. For example in my example line 2 and 4 have MyClassName and within the two line 4 has a SessionScope value different than token so line 4 should be output. I am struggling with the grep and backreference options.

• what is the token value ? – RomanPerekhrest Jun 21 '17 at 17:06
• @RomanPerekhrest On line 2 and 4 you can see that as token:[0238234234-3948-4d9] – datastax Jun 21 '17 at 17:10

Capture the token into a group and then test it using backreferences:

$grep 'MyClassName' log | grep -vE 'token:($[[:xdigit:]-]+$),SessionScope:\1,PageScope:\1,RequestScope:\1' blahblah MyClassName blah blah blah userId:[6729223726254951za],key:[09809890980980908d0e6],token:[0238234234-3948-4d9],SessionScope:[1111111-3948-4d9],PageScope:[0238234234-3948-4d9],RequestScope:[0238234234-3948-4d9], requestUrl:/blah/blah/blah  gawk solution: awk -v FPAT='\$[^][[:space:]]+\$' 'NF>5 && ($3!=$4 ||$3!=$5 ||$3!=$6){ print$0 }' logfile


The output:

blahblah MyClassName blah blah blah userId:[6729223726254951za],key:[09809890980980908d0e6],token:[0238234234-3948-4d9],SessionScope:[1111111-3948-4d9],PageScope:[0238234234-3948-4d9],RequestScope:[0238234234-3948-4d9], requestUrl:/blah/blah/blah


Details:

• -v FPAT='\$[^][[:space:]]+\$' - pattern defining field value (e.g. [0238234234-3948-4d9])

• ($3!=$4 || $3!=$5 || $3!=$6) - if any of the crucial keys doesn't match the token \$3 value