Finding the differences of two variables containing strings unix

6.5k Views Asked by At

How i use diff for variables instead of files.

All tutorials have examples with files but not with variables.

I want it to print just the differences.

for example:

TEXTA=abcdefghijklmnopqrstuvxyz; TEXTB=abcdefghijklmnopqrstuvxyr
2

There are 2 best solutions below

4
twalberg On BEST ANSWER

diff is a utility to compare two files. If you really want to compare two variables, and you are using bash for your shell, you can "fake it" this way:

diff <(echo ${TEXTA}) <(echo ${TEXTB})

Otherwise, you can just write your variables to two temporary files and compare them.

However, note that in your example, since each variable is a single line, it'll just tell you that they're different, unless you use a version of diff that will show you the specific positions in the line where they differ.

0
Anish On

I would use sdiff.

sdiff <(echo $TEXTA) <(echo $TEXTB)

sdiff points out just the differences between the two strings and shows them side-by-side separated by |.

abcdefghijklmnopqrstuvxyz  | abcdefghijklmnopqrstuvxyr

This can be useful when your string is too long. sdiff would highlight only the part of the string that is different.