Match with grep when pattern contains hyphen “-“

I wrote the following command in order to match $a with $b, but when the value includes “-“, then I get an error. How can I avoid that?

# a="-Xmx5324m"
# b="-Xmx5324m"
#
#
#  echo "$a"  | grep -Fxc "$b"
grep: conflicting matchers specified

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Place -- before your pattern:

echo "$a"  | grep -Fxc -- "$b"

-- specifies end of command options for many commands/shell built-ins, after which the remaining arguments are treated as positional arguments.

Method 2

Besides of @sebasth’s great answer, you could tell that PATTERN with grep's -e option to use PATTERN as a pattern (here using the <<< zsh here-string operator instead of echo; see also printf '%sn' "$a" for portability).

grep -Fxc -e "$b" <<<"$a"

Or all beside of other options.

grep -Fxce "$b" <<<"$a"

Since your goal is byte-to-byte string equality comparison use the [ command instead.

if [ "$a" = "$b" ]

Or if $a contains $b, using the [[...]] ksh construct:

if [[ $a == *"$b"* ]]

Or more portably in all Bourne-like shells:

case $a in
  *"$b"*) ...
esac


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x