Roland Turner

about | contact

Bash regexes

Bash now (v4.1.5) does special parser trickery with the argument to =~. The easiest way to work with this is to put the regular expression into its own environment variable. e.g. to get the SMTP transaction ID from an exim log

line='2010-07-20 00:06:08 L5TE67-000BPA-56 <= nagios@nms2.example H=(mail.example) [] P=esmtp S=22696 id=20100719170632.362CC12EDB7@nms2.example T="NMS Alert - Disk-D on Server2 is WARNING (111)" from <nagios@nms2.example> for admin@example'
re='^....-..-.. ..:..:.. (......-......-..) '
[[ $line =~ $re ]] && echo ${BASH_REMATCH[1]}