Linux bash that returns where two lines differ
So, I've searched for searches and also went into more detail about Stack Overflow, but I just can't seem to find an easy way to do exactly this:
I want to know how two lines (no spaces) differ from each other and just print what is the exact difference.
eg:.
Input 1 > "Chocolatecakeflavour"
Input 2 > "Chocolateflavour"
Output: "cake"
I've tried doing this with diff and dwdiff, cmp and other famous bash commands that popped into my mind, but I just couldn't get this exact result.
Any ideas?
+3
source to share
1 answer
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
- split the character of the input line by character (one in each line) -
diff
- get the difference in both lists (1 char in each line) -
awk '/[<>]/{printf $2}'
is to suppress<
OR>
from diff output and print everything on the same line
The EDIT: . As per the OP's comments below, if the lines are on different lines of the file, use:
f=file
diff <(fold -w1 <(sed '2q;d' $f)) <(fold -w1 <(sed '3q;d' $f)) | awk '/[<>]/{printf $2}'
cake
+5
source to share