Regular Expression : bash 3 vs bash 4 - regex

The follow code with a regular expression check does not outputs the same result between bash 3 and bash 4:
TESTCASE="testcase0"
[[ ${TESTCASE} =~ "^testcase[0-9\.]*$" ]]
echo $?
echo ${BASH_REMATCH}
bash 3.2 outputs a successful regular expression check:
0
testcase0
bash 4.1 fails the regular expression check:
1
<empty line>
I can't identify where in my regex pattern the expressions fails. I would need a code compatible between both version of bash.
Does anyone have a clue on what's my problem ?
Thanks !

In older versions of Bash (3.1), it was possible to use quotes around a regular expression in a test. In newer versions, the quotes are treated as part of the pattern, so the match fails.
The solution is to remove the quotes.
The recommended way to use regular expressions is this:
re='^testcase[0-9\.]*$' # single quotes around variable
[[ ${TESTCASE} =~ $re ]] # unquoted variable used in test
This syntax should work in all versions of bash that support regular expressions. The variable isn't strictly necessary but it improves readability. See the regular expressions section of Greg's wiki for more details.
Regarding the use of a variable (from the link above):
For cross-compatibility (to avoid having to escape parentheses, pipes and so on) use a variable to store your regex, e.g. re='^\*( >| *Applying |.*\.diff|.*\.patch)'; [[ $var =~ $re ]] This is much easier to maintain since you only write ERE syntax and avoid the need for shell-escaping, as well as being compatible with all 3.x BASH versions.
By the way, there's no need to escape the . inside the bracket expression.

Related

Bash variable substitution with a regex not working as expected

Given a bash variable holding the following string:
INPUT="Cookie: cf_clearance=foo; __cfduid=bar;"
Why is the substitution ${INPUT/cf_clearance=[^;]*;/} producing the output: Cookie: instead of what I'd expect: Cookie: __cfduid=bar;
Testing the same regex in online regex validators confirms that cf_clearance=[^;]*; should match cf_clearance=foo; only, and not the rest of the string.
What am I doing wrong here?
Use the actual regular-expression matching features instead of parameter expansion, which works with patterns.
[[ $INPUT =~ (.*)(cf_clearance=[^;]*;)(.*) ]]
ans=${BASH_REMATCH[1]}${BASH_REMATCH[3]}
You can also use an extended pattern, which is equivalent to a regular expression in power:
shopt -s extglob
$ echo "${INPUT/cf_clearance=*([^;]);/}"
Use sed:
INPUT=$(sed 's/cf_clearance=[^;]*;//' <<< "$INPUT")
Like you have been told in comments, bash parameter substitution only supports glob patterns, not regular expressions. So the problem is really with your expectation, not with your code per se.
If you know that the expression can be anchored to the beginning of the string, you can use the ${INPUT#prefix} parameter substitution to grab the shortest possible match, and add back the Cookie: in front:
echo "Cookie: ${INPUT#Cookie: cf_clearance=*;}"
If you don't have this guarantee, something very similar can be approximated with a pair of parameter substitutions. Find which part precedes cf_clearance, find which part follows after the semicolon after cf_clearance; glue them together.
head=${INPUT%cf_clearance=*}
tail=${INPUT#*cf_clearance=*;}
echo "$head$tail"
(If you are not scared of complex substitutions, the temporary variables aren't really necessary or useful.
echo "${INPUT%cf_clearance=*}${INPUT#*cf_clearance=*;}"
This is a little dense even for my sophisticated taste, though.)

BASH_REMATCH empty

I'm trying capture the some input regex in Bash but BASH_REMATCH comes EMPTY
#!/usr/bin/env /bin/bash
INPUT=$(cat input.txt)
TASK_NAME="MailAccountFetch"
MATCH_PATTERN="(${TASK_NAME})\s+([0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2})"
while read -r line; do
if [[ $line =~ $MATCH_PATTERN ]]; then
TASK_RESULT=${BASH_REMATCH[3]}
TASK_LAST_RUN=${BASH_REMATCH[2]}
TASK_EXECUTION_DURATION=${BASH_REMATCH[4]}
fi
done <<< "$INPUT"
My input is:
MailAccountFetch 2017-03-29 19:00:00 Success 5.0 Second(s) 2017-03-29 19:03:00
By debugging the script (VS Code+Bash ext) I can see the INPUT string matches as the code goes inside the IF but BASH_REMATCH is not populated with my two capture groups.
I'm on:
GNU bash, version 4.4.0(1)-release (x86_64-pc-linux-gnu)
What could be the issue?
LATER EDIT
Accepted Answer
Accepting most explanatory answer.
What finally resolved the issue:
bashdb/VS Code environment are causing the empty BASH_REMATCH. The code works OK when ran alone.
As Cyrus shows in his answer, a simplified version of your code - with the same input - does work on Linux in principle.
That said, your code references capture groups 3 and 4, whereas your regex only defines 2.
In other words: ${BASH_REMATCH[3]} and ${BASH_REMATCH[4]} are empty by definition.
Note, however, that if =~ signals success, BASH_REMATCH is never fully empty: at the very least - in the absence of any capture groups - ${BASH_REMATCH[0]} will be defined.
There are some general points worth making:
Your shebang line reads #!/usr/bin/env /bin/bash, which is effectively the same as #!/bin/bash.
/usr/bin/env is typically used if you want a version other than /bin/bash to execute, one you've installed later and put in the PATH (too):
#!/usr/bin/env bash
ghoti points out that another reason for using #!/usr/bin/env bash is to also support less common platforms such as FreeBSD, where bash, if installed, is located in /usr/local/bin rather than the usual /bin.
In either scenario it is less predictable which bash binary will be executed, because it depends on the effective $PATH value at the time of invocation.
=~ is one of the few Bash features that are platform-dependent: it uses the particular regex dialect implemented by the platform's regex libraries.
\s is a character class shortcut that is not available on all platforms, notably not on macOS; the POSIX-compliant equivalent is [[:space:]].
(In your particular case, \s should work, however, because your Bash --version output suggests that you are on a Linux distro.)
It's better not to use all-uppercase shell variable names such as INPUT, so as to avoid conflicts with environment variables and special shell variables.
Bash uses system libraries to parse regular expressions, and different parsers implement different features. You've come across a place where regex class shorthand strings do not work. Note the following:
$ s="one12345 two"
$ [[ $s =~ ^([a-z]+[0-9]{4})\S*\s+(.*) ]] && echo yep; declare -p BASH_REMATCH
declare -ar BASH_REMATCH=()
$ [[ $s =~ ^([a-z]+[0-9]{4})[^[:space:]]*[[:space:]]+(.*) ]] && echo yep; declare -p BASH_REMATCH
yep
declare -ar BASH_REMATCH=([0]="one12345 two" [1]="one1234" [2]="two")
I'm doing this on macOS as well, but I get the same behaviour on FreeBSD.
Simply replace \s with [[:space:]], \d with [[:digit:]], etc, and you should be good to go. If you avoid using RE shortcuts, your expressions will be more widely understood.

Where is lookaround regex supported and where isn't it?

Trying to improve my regex skills, I wanted to learn about lookahead and lookbehind expressions. On my Archlinux system I tried the following:
a=ab;if [[ $a =~ [a-z](?=b) ]]; then echo "Y";else echo "N";fi
Which, as far as I understand it, should match and thus echo out a "Y", but doesn't.
echo ab |sed 's/[a-z](?=b)/x/'
...also doesn't seem to match.
grep doesn't seem to lookaround either, but pcregrep does. I also tried several attempts on quoteing and/or escaping the expressions, to no avail.
I'm a little confused, now. Could someone please clarify where lookaround, which doesn't seem that exotic judging from the number of mentions in tutorials, can actually be used? Or did I just mess up escaping my expressions?
Lookaround assertions aren't supported by basic or extended posix regular expressions which are available in bash or sed.
A good tool to test is GNU grep which supports the -P option for perl compatible regular expressions. Like this:
grep --color=auto -P '[a-z](?=b)' <<< 'ab'
Even a greater resource are online regex testing tools like https://regex101.com/
You should distinguish between basic and extended Regular Expressions.
In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; They need to be escaped to get their "regex" meaning.
On the other hand, in the extended Regular Expressions, these characters get their "regex" meaning.
If you grep --help, you'll get:
-E, --extended-regexp PATTERN is an extended regular expression (ERE)
Note that grep doesn't support look-arounds, it's supported in pcregrep.

Why is Bash pattern match for ?(*[[:class:]])foobar slow?

I have a text file foobar.txt which is around 10KB, not that long. Yet the following match search command takes about 10 seconds on a high-performance Linux machine.
bash>shopt -s extglob
bash>[[ `cat foobar.txt` == ?(*[[:print:]])foobar ]]
There is no match: all the characters in foobar.txt are printable but there is no string "foobar".
The search should try to match two alternatives, each of them will not match:
"foobar"
that's instantenous
*[[:print:]]foobar
- which should go like this:
should scan the file character by character in one pass, each time, check if the next characters are
[[:print:]]foobar
this should also be fast, no way should take a millisecond per character.
In fact, if I drop ?, that is, do
bash>[[ `cat foobar.txt` == *[[:print:]]foobar ]]
this is instantaneous. But this is simply the second alternative above, without the first.
So why is this so long??
The glob matcher in bash is just not optimized. See, for example, this bug-bash thread, during which bash maintainer Chet Ramey says:
It's not a regexp engine, it's an interpreted-on-the-fly matcher.
Since bash includes a regexp engine as well (use =~ instead of == inside [[ ]]), there's probably not much motivation to do anything about it.
On my machine, the equivalent regexp (^(.*[[:print:]])?foobar$) suffered considerably from locale-aware [[:print:]]; for some reason, that didn't affect the glob matcher. Setting LANG=C made the regexp work fine.
However, for a string that size, I'd use grep.
As others have noted, you're probably better off using grep.
That said, if you wanted to stick with a [[ conditional - combining #konsolebox and #rici's advice - you'd get:
[[ $(<foobar.txt) =~ (^|[[:print:]])foobar$ ]]
Edit: Regex updated to match the OP's requirements - thanks, #rici.
Generally speaking, it is preferable to use regular expressions for string matching (via the =~ operator, in this case), rather than [globbing] patterns (via the == operator), whose primary purpose is matching file- and folder names.
Simply because you do many forks of bash (one for the subshell, and one for the cat command), and also, you read the cat binary as well while you execute it.
[[ `cat foobar.txt` == *[[:print:]]foobar ]]
This form would be faster:
[[ $(<foobar.txt) == *[[:print:]]foobar ]]
Or
IFS= read -r LINE < foobar.txt && [[ $LINE == *[[:print:]]foobar ]]
If it doesn't make a difference the speed of pattern matching could be related to the version of Bash you're using.

How to reference captures in bash regex replacement

How can I include the regex match in the replacement expression in BASH?
Non-working example:
#!/bin/bash
name=joshua
echo ${name//[oa]/X\1}
I expect to output jXoshuXa with \1 being replaced by the matched character.
This doesn't actually work though and outputs jX1shuX1 instead.
Perhaps not as intuitive as sed and arguably quite obscure but in the spirit of completeness, while BASH will probably never support capture variables in replace (at least not in the usual fashion as parenthesis are used for extended pattern matching), but it is still possible to capture a pattern when testing with the binary operator =~ to produce an array of matches called BASH_REMATCH.
Making the following example possible:
#!/bin/bash
name='joshua'
[[ $name =~ ([ao].*)([oa]) ]] && \
echo ${name/$BASH_REMATCH/X${BASH_REMATCH[1]}X${BASH_REMATCH[2]}}
The conditional match of the regular expression ([ao].*)([oa]) captures the following values to $BASH_REMATCH:
$ echo ${BASH_REMATCH[*]}
oshua oshu a
If found we use the ${parameter/pattern/string} expansion to search for the pattern oshua in parameter with value joshua and replace it with the combined string Xoshu and Xa. However this only works for our example string because we know what to expect.
For something that functions more like the match all or global regex counterparts the following example will greedy match for any unchanged o or a inserting X from back to front.
#/bin/bash
name='joshua'
while [[ $name =~ .*[^X]([oa]) ]]; do
name=${name/$BASH_REMATCH/${BASH_REMATCH:0:-1}X${BASH_REMATCH[1]}}
done
echo $name
The first iteration changes $name to joshuXa and finally to jXoshuXa before the condition fails and the loop terminates. This example works similar to the look behind expression /(?<!X)([oa])/X\1/ which assumes to only care about the o or a characters which don't have a X prefixed.
The output for both examples:
jXoshuXa
nJoy!
bash> name=joshua
bash> echo $name | sed 's/\([oa]\)/X\1/g'
jXoshuXa
The question bash string substitution: reference matched subexpressions was marked a duplicate of this one, in spite of the requirement that
The code runs in a long loop, it should be a one-liner that does not
launch sub-processes.
So the answer is:
If you really cannot afford launching sed in a subprocess, do not use bash ! Use perl instead, its read-update-output loop will be several times faster, and the difference in syntax is small. (Well, you must not forget semicolons.)
I switched to perl, and there was only one gotcha: Unicode support was not available on one of the computers, I had to reinstall packages.