0

$SQL_RESULT is usually something like this:

TDM_PROC
-------------------------------------------------------------------
N

I need to extract the last word from it (N in this case).

In bash 3.2 I used this expression:

if [[ $SQL_RESULT =~ "(\w+)$" ]] ; then
  RES=${BASH_REMATCH[1]}
else
  echo "Error" > $LOG_FILE
  exit 1
fi

I found that in bash 4 I should not use the quotes but it still does not work

if [[ $SQL_RESULT =~ (\w+)$ ]] ; then
  RES=${BASH_REMATCH[1]}
else
  echo "Error" > $LOG_FILE
  exit 1
fi

Any help appreciated.

2 Answers2

2

Use following BASH shell-option:

shopt -s compat31

to allow quoting in regex matching. With above option set you can do usual way:

if [[ $SQL_RESULT =~ "([A-Za-z0-9_]+)$" ]] ; then
  RES=${BASH_REMATCH[1]}
else
  echo "Error" > $LOG_FILE
  exit 1
fi
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

The following works for me in bash 4.0. Notice that I have used $'\n' to specify a newline before the (..) group. Additionally, I replace \w with .

 if [[ $SQL_RESULT =~ ^.*$'\n'(.+?)$ ]]; then RES=${BASH_REMATCH[1]}; else echo '

no'; fi

echo $RES
N
iruvar
  • 22,736
  • 7
  • 53
  • 82