I am trying the code below and hoping to get result as 0 (i.e. $? -eq 0) but for some reason it always fails:echo INBOUND_PATH|/tmp | grep -E '^\(INBOUND_PATH\)\|\(.*\)$';echo $?The reason I wanted to create a back reference is because if the string format was valid then I would cut out the directory with following command:g_inboundDir=grep -E 's/^\(INBOUND_PATH\)\|(.*)$/\2';
Linux grep with regular expression question
grep;regular expression
Bridging the gap and all answers together, and also looking at the man page of grep (man grep) , we have two main kinds of regular expressions: Basic Regex and Extended Regex.According to man grep :Basic vs Extended Regular Expressions         In  basic  regular  expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed  versions \?, +, {, \|, (,and ).In other words you can capture groups with single grep using escaped () like  grep \(....\) or if you use grep -E or egrep you dont need to escape parenthesis : egrep '(....)' Same rules apply to sed. A simple sed understands basic regular expressions thus you need escaping to capture groups : sed 's/\(....\)\(...\)/\2/' or you can enable extended regex support in sed with -E or -r switch (depending on sed implementation) : sed -E 's/(...)(...)/\2/' As a result all bellow commands are valid:$ echo INBOUND_PATH|/tmp | grep '^\(INBOUND_PATH\)|\(.*\)$';echo $?INBOUND_PATH|/tmp0$ echo INBOUND_PATH|/tmp | egrep '(INBOUND_PATH)\|(.*)$';echo $?INBOUND_PATH|/tmp0$ echo INBOUND_PATH|/tmp | sed 's/^\(INBOUND_PATH\)|\(.*$\)/\2/'/tmp$ echo INBOUND_PATH|/tmp | sed -E 's/(INBOUND_PATH)\|(.*)$/\2/'/tmpMind the opossite handling of special symbols in different Regexes.   For example see the handling of pipe | symbol in above commands:In basic regex (BRE):You don't need to escape pipe symbol to match a literal pipe symbol.Escaping pipe symbol in BRE, will be considered as an OR operator (which accidentaly will work in your case).  Similarilly , in BRE you don't need to escape parenthesis ( ) to match a literal parenthesis but you need to escape parenthesis to capture a group.In extended regex (ERE):You need to escape the pipe symbol in order to be matched literally, since by default in ERE pipe symbol is treated as OR operator (opposite handling compared to BRE)   Similarilly in ERE you need to escape parenthesis to match a literall parenthesis (, since by default parenthesis in ERE is used to capture groups.