Home > Blockchain >  Bash check string that don't match on order
Bash check string that don't match on order

Time:09-21

how to compare string in bash? I only want to compare words, not word order for example i have variable

VAR1=eu-endpoint-2021.09.20 prod-store-2021.09.20 service-trace-2021.09.20

and another variable that stores the same info but with different order

VAR2=prod-store-2021.09.20 eu-endpoint-2021.09.20 service-trace-2021.09.20

and how can i compare this only by words? nor the words order for example

if $VAR1 == $VAR2 
then
do smth;
else
do smth;
fi

CodePudding user response:

Since both your input string only contains parts that don't contain any spaces, we can


#!/bin/bash

VAR1='eu-endpoint-2021.09.20 prod-store-2021.09.20 service-trace-2021.09.20'
VAR2='prod-store-2021.09.20 eu-endpoint-2021.09.20 service-trace-2021.09.20'

ARR1=($VAR1)
ARR2=($VAR2)

RES=1

for i in "${ARR1[@]}"; do
    [[ ! " ${ARR2[*]} " =~ " ${i} " ]] && RES=0 && break
done

[ $RES -eq 1 ] && echo 'Equal' || echo 'Not equal'

  • Will show Equal for the provided example strings as you can try here.
  • If you change any of the strings, you'll get Not equal as you can try here.

CodePudding user response:

I'd just sort them then compare the result, e.g.:

$ VAR1='eu-endpoint-2021.09.20 prod-store-2021.09.20 service-trace-2021.09.20'
$ VAR2='prod-store-2021.09.20 eu-endpoint-2021.09.20 service-trace-2021.09.20'

<p>

$ if [[ $(tr ' ' '\n' <<<"$VAR1" | sort) = $(tr ' ' '\n' <<<"$VAR2" | sort) ]]; then echo same; else echo diff; fi
same
  •  Tags:  
  • bash
  • Related