Home > Enterprise >  how to do a character comparison in bash?
how to do a character comparison in bash?

Time:11-25

lets say I have a column showing 2/2 and I want to compare if the left side of the separator which in this case is / is matching with the right side? is there any way to achieve this in bash?

one possible method is using IFS but that requires to store the values in variables and then compare them using IF statement. I am trying to achieve this using a oneliner command.

CodePudding user response:

You can use bash expansion operators to extract each part and compare them directly.

var='2/2'
if [[ "${var%/*}" = "${var#*/}" ]]
then echo match
else echo no match
fi

${var%/*} removes the end of the variable matching the wildcard /*, so it gets the first number. ${var#*/} removes the beginning of the variable match the wildcard */, so it gets the second number.

CodePudding user response:

Although you are seeking for the bash solution, how about an awk option:

col="2/2"
echo "$col" | awk -F/ '{print $1==$2 ? "match" : "no match"}'
  • The -F/ option sets the awk's field separator to /.
  • Then the input is split on / and the awk variable $1 is assigned to the left side while $2 is assigned to the right side.
  • Now we can compare $1 and $2.
  • Related