0

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?

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

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

Btw, there is no file named hey and hi in the example below. Hence, explaining the No such file or directory error message

wolf@linux:~$ diff hey hi
diff: hey: No such file or directory
diff: hi: No such file or directory
wolf@linux:~$ 
  • Compare, in what sense? What do you want as output? What are your strings? – Kusalananda Apr 27 at 9:10
  • What do you expect as output from diff hey hi? – Kusalananda Apr 27 at 9:15
  • Thanks for your response, I've just updated the question with more details. – Wolf Apr 27 at 9:16
1

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).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.