bash bash中两个字符串之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20046482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:39:56  来源:igfitidea点击:

diff between two strings in bash

bashdiff

提问by georgiana_e

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

我有两个包含信息行的字符串。我想获得两个字符串中不同的行。示例:字符串 1:

"This is line1
This is line2
This is line3"

String2:

字符串2:

"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"

回答by devnull

You could use comm:

你可以使用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

回答by kenichi

You could do smth like what you want namely with diff

你可以随心所欲 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

受此问题和答案的启发:Bash 字符串差异