diff two multilines bash variables to list what lines aren't in the other

Question about comparing two multi-line Bash variables to identify lines that aren't present in the other variable. To accomplish this task, you can use various Bash commands and techniques. Here's one common approach:


Suppose you have two multi-line variables, `$variable1` and `$variable2`, and you want to find lines that are in one variable but not in the other.


Here's a general script you can use:


```bash

# Split variables into arrays

IFS=$'\n' read -rd '' -a array1 <<< "$variable1"

IFS=$'\n' read -rd '' -a array2 <<< "$variable2"


# Find lines in variable1 that aren't in variable2

for line in "${array1[@]}"; do

  if [[ ! " ${array2[*]} " == *" $line "* ]]; then

    echo "$line is in variable1 but not in variable2"

  fi

done


# Find lines in variable2 that aren't in variable1

for line in "${array2[@]}"; do

  if [[ ! " ${array1[*]} " == *" $line "* ]]; then

    echo "$line is in variable2 but not in variable1"

  fi

done

```


This script does the following:


1. Splits the multi-line variables into arrays using the newline character (`$'\n'`) as the delimiter.

2. Iterates through each line in `variable1`, checking if it's in `variable2` using the conditional statement. If not, it prints a message indicating that the line is in `variable1` but not in `variable2`.

3. Then, it repeats the process for lines in `variable2` that are not in `variable1`.


This script will list the lines that are unique to each variable, helping you identify the differences.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?