I came across below statement here:
To include
]
in the list of characters matched by a bracket expression, make it the first character (or first after^
for a negated set):[]abc]
or[^]abc]
(not).[abc]]
nor[abc\]]
So I tried out kind of below border case of matching and replacing both [
and ]
:
echo '[]' | sed 's/[[]/^/' #only [ in matching string (works)
echo '[]' | sed 's/[[]]/^/' #both [] in matching string (fails #1)
echo '[]' | sed 's/[\[\]]/^/' #escaping both [] in matching string (fails #2)
echo '[]' | sed 's/[][]/^/' #including ] as first character (as suggested by above quoted point) inside [..] leads to [][] pattern (fails #3)
echo '[]' | sed 's/[]]/^/' #only ] in matching string (works)
Output was:
^]
^
^
^]
[^
In failures above, I felt it should have printed ^^
, that is, replacing both square brackets in []
with ^
. I have numbered failures #1
, #2
and #3
.. Can someone please explain the reason behind the output I am getting in each of these failures and what should be the way to make it work when I want to match both [
and ]
?