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
- Convert the strings into arrays
($VAR1)
- Loop over array1: Loop through an array of strings in Bash?
- Check if current element exist in array2: Check if a Bash array contains a value
- If not, set result to
false
, andbreak
out of the loop
- If not, set result to
#!/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