[英]Compare two text files line by line, finding differences but ignoring numerical values differences
我正在编写一个 bash 脚本来逐行比较两个相似的文本文件并找到文件的每一行之间的最终差异,我应该指出差异并告诉差异在哪一行,但我应该忽略数值在这个比较中。
例子 :
Process is running; process found : 12603 process is listening on port 1200
Process is running; process found : 43023 process is listening on port 1200
在上面的示例中,脚本不应该发现任何差异,因为它只是进程 ID,并且它一直在变化。
但除此之外,我希望它通知我行之间的差异。
例子 :
Process is running; process found : 12603 process is listening on port 1200
Process is not running; process found : 43023 process is not listening on port 1200
我已经有一个工作脚本来查找差异,并且我使用以下函数来查找差异并忽略数值,但它不能完美地工作,有什么建议吗?
COMPARE_FILES()
{
awk 'NR==FNR{a[FNR]=$0;next}$0!~a[FNR]{print $0}' $1 $2
}
其中 $1 和 $2 是要比较的两个文件。
请您尝试以下方法:
COMPARE_FILES() {
awk '
NR==FNR {a[FNR]=$0; next}
{
b=$0; gsub(/[0-9]+/,"",b)
c=a[FNR]; gsub(/[0-9]+/,"",c)
if (b != c) {printf "< %s\n> %s\n", $0, a[FNR]}
}' "$1" "$2"
}
有什么建议么 ?
在进行比较之前 Jettison 数字,我会按照替换方式改进您的代码
NR==FNR{a[FNR]=$0;next}$0!~a[FNR]{print $0}
使用
NR==FNR{a[FNR]=$0;next}gensub(/[[:digit:]]/,"","g",$0)!~gensub(/[[:digit:]]/,"","g",a[FNR]){print $0}
说明:我利用gensub
字符串函数,因为它确实返回了新字符串( gsub
更改所选变量值)。 我用空字符串替换[:digit:]
字符(即删除它) g
lobly。
使用任何 awk:
compare_files() {
awk '{key=$0; gsub(/[0-9]+(.[0-9]+)?/,RS,key)} NR==FNR{a[FNR]=key; next} key!~a[FNR]' "${@}"
}
上面不只是删除数字,它会替换每组数字,无论它们是像17
这样的整数还是像17.31
这样的小数,用RS
的内容(默认为换行符)以避免错误匹配,例如:
file1: foo 1234 bar
file2: foo bar
如果您只是删除数字,那么这两行错误地变得相同:
file1: foo bar
file2: foo bar
而如果您用换行符替换数字,那么它们正确地保持不相同:
file1: foo
bar
file2: foo bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.