user3093942 user3093942 - 2 months ago 14
Perl Question

how to get value of a specific grepped pattern using awk

Looking out to get value of X_RULE only. My input file might have patterns like

TMP_LEARN A B
-antmove [ X_RULE = "STUDENT" ]
-antmove [ X_CLASS = "COMMERCE" ]
-antmove [ X_DISCRIPTION = "COLLEGE STUDENTS" ]
...
...


TMP_PROP -antmove [ X_RULE = "STUDENT" ] -antmove [ X_CLASS = "SCIENCE" ] .....


Simple

grep "X_RULE" inputFile |awk -F " " '{print $1}'


will return correct results for first pattern but won't work on second pattern. How can I use

regex( i.e -- (/^\s*\[\s*X_RULE\s*=\s*([^\]]+)\]) ...)


on shell to segregate the value in this case?

Regards,
Divesh

Answer

You can use this common regex for both lines of input in grep -oP:

grep -oP 'X_RULE\s*=\s*"\K[^"]+' file

STUDENT
STUDENT

RegEx Breakup:

X_RULE  # match literal text X_RULE
\s*=\s* # match = surrounded by optional spaces on each side
"       # match starting double quote
\K      # match reset to forget what we've matched so far
[^"]+   # match 1 or more of anything that is not " to get desired value
Comments