Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

diff between two strings in bash

Tags:

bash

diff

I have two strings containing lines of information. I want to obtain the lines that are different in the two strings. Example: String1:

"This is line1
This is line2
This is line3"

String2:

"This is line1
This is linex
This is line2"

Result expected:

diff string1 string2 is:
"This is line3"

diff string2 string1 is:
"This is linex"
like image 949
georgiana_e Avatar asked Nov 18 '13 11:11

georgiana_e


2 Answers

You could use comm:

$ str1="This is line1
> This is line2
> This is line3"
$ str2="This is line1
> This is linex
> This is line2"

$ comm -23 <(echo "$str1" | sort) <(echo "$str2" | sort)
This is line3
$ comm -23 <(echo "$str2" | sort) <(echo "$str1" | sort)
This is linex
like image 59
devnull Avatar answered Sep 28 '22 06:09

devnull


You could do smth like what you want namely with diff

$ str1="This is line1\nThis is line2\nThis is line3"; str2="This is line1\nThis is linex\nThis is line2";
$
$ diff -y -W 30 --suppress-common-lines <(echo -e $str1) <(echo -e $str2)
              > This is linex
This is line3 <

Inspired by this question&answers: Bash string difference

like image 38
kenichi Avatar answered Sep 28 '22 05:09

kenichi