3

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
Tamalero
  • 471
  • 1
  • 7
  • 14

2 Answers2

9

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.

twalberg
  • 59,951
  • 11
  • 89
  • 84
  • 1
    Wa, how does that work? Does bash create temp files on the fly for us? `echo <(echo ${TEXTA})` outputs `/dev/fd/63`, so it seems so. Is it bash magic of is it POSIX? – Ciro Santilli OurBigBook.com Nov 13 '13 at 15:20
  • 1
    It's a `bash` feature - it replaces the `<(command)` with the name of a "file" that appears to contain the output of `command`. It may or may not actually create a file, depending on your platform - in your example it appears to use a pipe instead of actually creating a file. The manual page for `bash` might be an interesting read... – twalberg Nov 13 '13 at 15:23
  • 1
    Ok, the feature is called process substitution. Seems to be a bash extension to POSIX. Nice. – Ciro Santilli OurBigBook.com Nov 13 '13 at 15:27
  • In the example I just put one difference, but in my thing I'm having more, thanks =D – Tamalero Nov 14 '13 at 09:52
0

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.

Anish
  • 189
  • 2
  • 6