5

So, I've been googling around, and also searching in more detail on stack overflow, but I just can't seem to find an easy way of doing exactly this:

I want to know in what way two strings (without whitespace) differ, and simply print what that exact difference is.

E.g.:

Input 1 > "Chocolatecakeflavour"
Input 2 > "Chocolateflavour"

Output: "cake"

I've tried doing this with diff and dwdiff, cmp, and other known bash commands that popped into mind, but I just couldn't get this exact result.

Any ideas?

2
  • That is a hard problem, depending on the amount of differences and the length of the input text. Have a look at diff, match and patch algorithms they might set you on the right path. Commented Oct 23, 2014 at 9:45
  • What should the output be if input 1 is "foo" and input 2 is "bar"? Commented Oct 23, 2014 at 9:49

1 Answer 1

9

You can use diff with fold and awk like ths:

s="Chocolatecakeflavour"
r="Chocolateflavour"

diff <(fold -w1 <<< "$s") <(fold -w1 <<< "$r") | awk '/[<>]/{printf $2}'
cake
  • fold -w1 is to split input string character by character (one in each line)
  • diff is to get difference in both lists (1 char in each line)
  • awk '/[<>]/{printf $2}' is to suppress < OR > from diff'e output and print everything in same line

EDIT: As per OP's comments below if strings are in different lines of a file then use:

f=file
diff <(fold -w1 <(sed '2q;d' $f)) <(fold -w1 <(sed '3q;d' $f)) | awk '/[<>]/{printf $2}'
cake
Sign up to request clarification or add additional context in comments.

1 Comment

Somehow, for my specific needs this doesn't do what I want. (although I dont understand how) My input 1 and input 2 are on different lines in a file, so I use sed '2q;d' and sed '3q;d' to get them from the file like this: diff --normal <(fold -w1 <<< <(echo sed '2q;d' AdaptiveMutants)) <(fold -w1 <<< <(echo sed '3q;d' AdaptiveMutants)) | awk '/[<>]/{printf $2}' Somehow though, this returns a '32', which is definitely not part of the input strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.