Reputation: 24423
I need to check if a variable contains a particular character, for use in an if-conditional in BASH, e.g.:
if [ "①" is in "$numbers" ]
then
echo "Found."
else
echo "Not found."
fi
If $numbers
is "These are some numbers 1232", it returns "Not found.", but if "①" is found anywhere in the line, it returns "Found."
I have been using $numbers | grep -c ①
, then checking if the output is greater than "0", but it seems there must be a simpler solution.
Upvotes: 2
Views: 74
Reputation: 241988
Right hand side of a comparison can be a pattern:
if [[ $numbers = *①* ]] ; then
Upvotes: 3
Reputation: 113924
For a posix solution, use a case
statement in place of an if
statement:
numbers="①"
case "$numbers" in
*①*) echo "Found it." ;;
*) echo "Not here." ;;
esac
This solution will work under dash
which is the default shell (/bin/sh
) for scripts under Debian-influenced distributions.
Upvotes: 2
Reputation: 648
As long as it's bash and doesn't need to be posix:
if [[ "$numbers" =~ ① ]]; then
echo "Found"
fi
Upvotes: 3