So I was trying to write a regex in grep to match square brackets, i.e [ad]
should match [
and ]
. But I was getting different results on using capturing groups and character classes. Also the result is different on putting '
in the beginning and end of regex string.
So these are the different result that I am getting.
Using capturing groups works fine
echo "[ad]" | grep -E '(\[|\])'
[ad]
Using capturing groups without '
gives syntax error
echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('
using character class with [
followed by ]
gives no output
echo "[ad]" | grep -E [\[\]]
Using character class with ]
followed by [
works correctly
echo "[ad]" | grep -E [\]\[]
[ad]
Using character class with ]
followed by [
and using '
does not work
echo "[ad]" | grep -E '[\]\[]'
It'd be great if someone could explain the difference between them.