1

This answer shows how to diff two strings - Using the diff command to compare two strings?

I try:

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

The output is:

1c1
< tring1
---
> string2

This shows that the two strings are different.

I would like to know at which characters the two strings are different, or at least the first character where the difference starts. How can I do it?

This is important when comparing long urls.

I study other answers based on git diff at diff within a line

I try

git diff --word-diff --word-diff-regex=. <( printf '%s\n' "tring1" ) <( printf '%s\n' "string2" )

The output is:

diff --git a/dev/fd/63 b/dev/fd/62
index 9234a649..b6ce327a 120000
--- a/dev/fd/63
+++ b/dev/fd/62
@@ -1 +1 @@
pipe:[69160538[-6-]{+8+}]

I am not sure if I apply git diff correctly and how to interpret the output.

Viesturs
  • 933
  • 3
  • 10
  • 15
  • 1
    Does this answer your question? [diff within a line](https://unix.stackexchange.com/questions/11128/diff-within-a-line) – Stephen Kitt Nov 16 '21 at 10:33
  • @StephenKitt if `git diff` has this functionality then it is better to provide a straitghtforward solution. – Viesturs Nov 16 '21 at 10:52
  • Please [edit] your question and show us the kind of output you are expecting. Does this need to be something like "the two strings differ at positions 1 and 7"? – terdon Nov 16 '21 at 10:56
  • @terdon counting positions could be complicated in long strings. A more appropriate output is showing insertions and deletions in the string. – Viesturs Nov 16 '21 at 10:59

2 Answers2

3

For your specific use-case, store the strings in files, and compare those with git diff:

$ echo tring1 > f1
$ echo string2 > f2
$ git diff --word-diff --word-diff-regex=. --no-index f1 f2
diff --git a/f1 b/f2
index e8ae123..d704b3b 100644
--- a/f1
+++ b/f2
@@ -1 +1 @@
{+s+}tring[-1-]{+2+}

This shows that the “s” character was added at the start of the string, and that “1” became “2”.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
3
cmp -b <( printf '%s\n' "tring1" ) <( printf '%s\n' "string2" )
/dev/fd/63 /dev/fd/62 differ: byte 1, line 1 is 164 t 163 s

cmp - compare two files byte by byte

nezabudka
  • 2,376
  • 5
  • 15