Issue
Suppose, I have a file like below:
aaa1bbb
aaa^bbb
aaa\bbb
aaa%bbb
aaa*ccc
aaa(ccc
aaa)bbb
I want to find all lines that contain either ^
or %
and then bbb
. My expected results:
aaa^bbb
aaa%bbb
When I execute grep '[^%]bbb' t1
I have received
aaa1bbb
aaa^bbb
aaa\bbb
aaa)bbb
which is completely correct. ^
is metacharter in grep []
syntax. I have all the results except %bbb
regex. I understand this. I have tried to disable metacharacter with \
like this: grep '[\^%]bbb' t1
I have received:
aaa^bbb
aaa\bbb
aaa%bbb
Why I got line aaa\bbb
in the results? The problem is: How do you disable the special meaning of the ^
character in grep []
syntax? Is it possible without using fgrep
or other workarounds?
Solution
To make a ^
literal char inside a bracket expression, put it NOT at the start of it:
grep '[%^]bbb' t1
This is part of the so-called "smart placement" technique, e.g. to use a ]
inside a bracket expression it must be placed at the start of a bracket expression, and -
should be either at the start or end of the bracket expression.
See an online demo:
#!/bin/bash
s='aaa1bbb
aaa^bbb
aaa\bbb
aaa%bbb
aaa*ccc
aaa(ccc
aaa)bbb'
grep '[%^]bbb' <<< "$s"
Output:
aaa^bbb
aaa%bbb
Answered By - Wiktor Stribiżew Answer Checked By - Terry (WPSolving Volunteer)