0
GREEN='\033[0;32m'
NC='\033[0m' # No Color

rimip2=$(echo -e "${GREEN}222b:b33c:3401:2341:88c2:85d7:5cf6:6a01${NC}" | grep "222b:b33c:3401:2341:88c2:85d7:5cf6:6a01")  

 if [[ "${rimip2}" == "222b:b33c:3401:2341:88c2:85d7:5cf6:6a01" ]]; then
     echo "#### Same"
 else
   echo "#### Different"
 fi

This code always print "#### Different" although the visible displayed value of echo ${rimip2} is 222b:b33c:3401:2341:88c2:85d7:5cf6:6a01

If I remove ${GREEN} and ${NC}, then "#### Same" is displayed.

This is a simplified portion of a complex code. So my aim is to maintain printing in GREEN color, and then grepping that line which I will use for ssh. But now I cannot use it for SSH until it is equal to the string value "222b:b33c:3401:2341:88c2:85d7:5cf6:6a01"

How can remove the Green encoding part after grepping the line?

electricalbah
  • 2,227
  • 2
  • 22
  • 36

2 Answers2

1

You can use grep -o to print only the part that matched the expression, so that the presence of any colour codes no longer makes a difference:

rimip2=$(echo -e "${GREEN}222b:b33c:3401:2341:88c2:85d7:5cf6:6a01${NC}" | grep -o "222b:b33c:3401:2341:88c2:85d7:5cf6:6a01")

You can also just use the exit status from grep directly, at least in this simplified case:

 if echo -e "${GREEN}222b:b33c:3401:2341:88c2:85d7:5cf6:6a01${NC}" | grep "222b:b33c:3401:2341:88c2:85d7:5cf6:6a01" >/dev/null; then
     echo "#### Same"
 else
   echo "#### Different"
 fi
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • grep has a silent mode if you just want the status `-q` – Gem Taylor Oct 21 '19 at 15:24
  • In this example, `-q` would be fine. But if you also want to handle errors, you can't use it, because it exits with status code 0 in case of error too. See: https://stackoverflow.com/questions/4749330/how-to-test-if-string-exists-in-file-with-bash/4749368#4749368 – Thomas Oct 22 '19 at 07:06
0

This Worked out

GREEN='\033[0;32m'
NC='\033[0m' # No Color
    rimip2=$(echo -e "${GREEN}240b:c01c:221:2341:88c2:85d7:5cf6:6a01${NC}" | grep "240b:c01c:221:2341:88c2:85d7:5cf6:6a01" | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g")  

     if [[ "${rimip2}" == "240b:c01c:221:2341:88c2:85d7:5cf6:6a01" ]]; then
         echo "#### Same"
     else
       echo "#### Different"
     fi
electricalbah
  • 2,227
  • 2
  • 22
  • 36