3

I am matching a regular expression in bash on OS X 10.11:

$ msg='[4]  the message'
$  [[ $msg =~ (.+)\t(.+) ]]
$ echo ${BASH_REMATCH[1]}
[4]
$ echo ${BASH_REMATCH[2]}
he message

Between the ']' and the 't' of $msg is a tab character. There is no tab in either ${BASH_REMATCH[1]} or ${BASH_REMATCH[2]}. Where did the 't' go?

  • I think you'll find there's is a tab in ${BASH_REMATCH[1]} (for the reason explained in @xhienne's answer i.e. $msg is getting split on the literal t) - but the unquoted variable is subject to word splitting by the shell; you'd have seen it if you'd done echo "${BASH_REMATCH[1]}" – steeldriver Mar 20 '17 at 18:30
  • Try it. I get nothing following the ]. Which is what confused me. – Mitchell Model Mar 21 '17 at 23:19
  • msg='[4] the message' ; [[ $msg =~ (.+)\t(.+) ]] ; echo "${BASH_REMATCH[1]}" | od -tx1 ==> 0000000 5b 34 5d 09 0a (5d is the closing ], and 09 is the tab) – steeldriver Mar 21 '17 at 23:39
5

The 't' is between the two sub-regex: \t, which isn't interpreted as a tabulation but as t. A tabulation would be $'\t'.

Try this instead:

$ msg=$'[4]\tthe message'
$ [[ "$msg" =~ (.+)$'\t'(.+) ]]
$ echo ${BASH_REMATCH[1]}
[4]
$ echo ${BASH_REMATCH[2]}
the message

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.