首页 > 解决方案 > 与 shell 脚本中元素位置的行差异

问题描述

输入:

文件1.txt

abc 1 2 3 4

文件2.txt

abc 1 2 5 6

预期输出:

differences is 
3 
5
at location 3

我可以使用以下方法跟踪差异:

comm -3 file1.txt file2.txt | uniq -c | awk '{print $4}' | uniq

但无法跟踪元素位置

你们能否建议使用shell脚本来跟踪元素位置?

标签: shelltext-fileselementtracking

解决方案


为了方便起见,使用 perl 和 CPAN 中的 Path::Class

perl -MPath::Class -MList::Util=first -e '
    @f1 = split " ", file(shift)->slurp;
    @f2 = split " ", file(shift)->slurp;
    $idx = first {$f1[$_] ne $f2[$_]} 0..$#f1;
    printf "difference is\n%s\n%s\nat index %d\n", $f1[$idx], $f2[$idx], $idx;
' file{1,2}.txt
difference is
3
5
at index 3

推荐阅读