1

It seems that I can't get word boundaries to work in [[:

$ echo foo | md5sum
d3b07384d113edec49eaa6238ad5ff00  -
$ [[ "$(echo foo | md5sum)" =~ ^d3b07384d113edec49eaa6238ad5ff00 ]] && echo ok
ok
$ [[ "$(echo foo | md5sum)" =~ ^d3b07384d113edec49eaa6238ad5ff00\b ]] && echo ok
$  ## no output 

Are word boundaries not accepted in [[? Or am I missing something?

  • http://stackoverflow.com/q/9792702/716443 – DavidO Jun 20 '14 at 15:48
  • @DavidO, I'm doing it like this: `[[ "$(echo foo | md5sum)" =~ ^d3b07384d113edec49eaa6238ad5ff00\\b ]] && echo ok`. No luck with that :( –  Jun 20 '14 at 15:50
  • Yes, that link I posted suggests putting your pattern in a separate variable. I also tried the `\\b` and wasn't successful, but didn't try the link's solution. – DavidO Jun 20 '14 at 15:51
  • ...and in testing, that doesn't work either. ;) – DavidO Jun 20 '14 at 15:52
  • `echo foo | md5sum | perl -nE 'say "ok" if m/^\bd3b07384d113edec49eaa6238ad5ff00\b/'` – DavidO Jun 20 '14 at 16:07
  • Is word boundary the real problem or is it a delimiter problem? –  Jun 20 '14 at 16:14
  • It appears to be a delimiter (or quoting) issue. Word boundary should be fine, but the bare backslashes are confusing the shell (my theory) – DavidO Jun 20 '14 at 16:15

2 Answers2

0

This seems to work, although it's a bit verbose:

[[ "$(echo foo | md5sum)" =~ $(echo '^d3b07384d113edec49eaa6238ad5ff00\b') ]] && echo ok

gbrener
  • 5,365
  • 2
  • 18
  • 20
0

The problem seems related to the backslash losing the meaning you intend when interpreted by the shell. There's probably some incantation of quoting that would eliminate the issue, but for me it's sometimes just easier to dump the output of a construct into Perl for further processing.

If you can accept a solution that invokes Perl on your system, this works:

echo foo | md5sum | perl -nE 'say "ok" if m/^\bd3b07384d113edec49eaa6238ad5ff00\b/'

If you're stuck with a Perl that predates v5.10, then this:

echo foo | md5sum | perl -lne 'print "ok" if m/^\bd3b07384d113edec49eaa6238ad5ff00\b/'

The solution is fairly self-explanatory if you read through perlrun, which explains what the various command line switches do. We're using -n to cause Perl to process some input, -E to tell Perl to evaluate some code using modern (5.10+) features (say), and the rest just reads as you would expect.

For older Perl versions (pre-5.10), say wasn't available, so the command line switches change to -l, -n, and -e: The first strips newlines from input (not useful), and adds them to output (useful, because print doesn't do that, where the newer say does). And the -e to evaluate some code using pre-5.10 semantics.

DavidO
  • 13,812
  • 3
  • 38
  • 66