sijo0703
sijo0703

Reputation: 567

how to match a whole substring with delimiter in bash

I have a String like this

"ABCD EFGH IJKL MNOP"

I get user input to match with each of these substrings as whole and not part. How do I do this?

This is what I am doing currently

printf "\n Enter user input:"

read userinput

INPUT=$userinput

if echo "ABCD EFGH IJKL MNOP" | grep -q "$INPUT"; then
  echo "Matching...";
else

  echo "Invalid entry ";
fi

The problem with the above code is it will match a partial substring like "ABC",

"GH" etc which I do not want. I just need the user input to compare with whole substrings separated by delimiter.

Upvotes: 0

Views: 79

Answers (2)

thepace
thepace

Reputation: 2221

grep -w

   -w, --word-regexp
          Select  only  those  lines  containing  matches  that form whole
          words.  The test is that the matching substring must  either  be
          at  the  beginning  of  the  line,  or  preceded  by  a non-word
          constituent character.  Similarly, it must be either at the  end
          of  the  line  or  followed by a non-word constituent character.
          Word-constituent  characters  are  letters,  digits,   and   the
          underscore.

Similar link: grep -w with only space as delimiter

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

Use -w to match an entire word in grep

echo "ABCD EFGH IJKL MNOP" | grep -w "$INPUT";

Example

>>> INPUT=ABC
>>> echo "ABCD EFGH IJKL MNOP" | grep -w "$INPUT";
>>>
>>> INPUT=ABCD
>>> echo "ABCD EFGH IJKL MNOP" | grep -w "$INPUT";
ABCD EFGH IJKL MNOP

Upvotes: 1

Related Questions