26

According to https://www.computerhope.com/unix/udiff.htm

The diff command analyzes two files and prints the lines that are different.

Can I use the same diff command to compare two strings?

$ more file*
::::::::::::::
file1.txt
::::::::::::::
hey
::::::::::::::
file2.txt
::::::::::::::
hi
$ diff file1.txt file2.txt 
1c1
< hey
---
> hi

Instead of saving the content of hey and hi into two different files, can I read it directly?

By the way, there are no files named hey or hi in the example below, which is why I get No such file or directory error messages.

$ diff hey hi
diff: hey: No such file or directory
diff: hi: No such file or directory
Kusalananda
  • 333,661
Wolf
  • 1,631

2 Answers2

28

Yes, you can use diff on two strings, if you make files from them, because diff will only ever compare files.

A shortcut way to do that is using process substitutions in a shell that supports these:

diff <( printf '%s\n' "$string1" ) <( printf '%s\n' "$string2" )

Example:

$ diff <( printf '%s\n' "hey" ) <( printf '%s\n' "hi" )
1c1
< hey
---
> hi

In other shells,

printf '%s\n' "$string1" >tmpfile
printf '%s\n' "$string2" | diff tmpfile -
rm -f tmpfile

In this second example, one file contains the first string, while the second string is given to diff on standard input. diff is invoked with the file containing the first string as its first argument. As its second argument, - signals that it should read standard input (on which the second string will arrive via printf).

Kusalananda
  • 333,661
0

For folks wishing to use strings instead of files input for the 'diff' command in Script Editor (AppleScript), I found the following worked after some toil:

do shell script "bash -c 'diff -y <(echo '\\''" & string1 & "'\\'') <(echo '\\''" & string2 & "'\\'')'

Note the need to present the code as a string to be run within the bash shell and the wicked escape tokens.

Antony
  • 11