diff 行大体相同但乱序的地方?

use*_*394 29 command-line diff

我想区分两组 mod_rewrite 规则。这组行大约有 90% 相同,但顺序如此不同以至于 diff 基本上说它们完全不同。

无论行号如何,如何查看两个文件之间哪些行真正不同?

Sha*_*off 42

sort可用于将文件按相同顺序排列,以便diff比较它们并识别差异。如果您有进程替换,您可以使用它并避免创建新的排序文件。

diff <(sort file1) <(sort file2)
Run Code Online (Sandbox Code Playgroud)


l0b*_*0b0 8

我为此编写了一个脚本,以保持行序不变。这是重要行的注释版本:

# Strip all context lines
diff_lines="$(grep '^[><+-] ' | sed 's/^+/>/;s/^-/</')" || exit 0

# For each line, count the number of lines with the same content in the
# "left" and "right" diffs. If the numbers are not the same, then the line
# was either not moved or it's not obvious where it was moved, so the line
# is printed.
while IFS= read -r line
do
    contents="${line:2}"
    count_removes="$(grep -cFxe "< $contents" <<< "$diff_lines" || true)"
    count_adds="$(grep -cFxe "> $contents" <<< "$diff_lines" || true)"
    if [[ "$count_removes" -eq "$count_adds" ]]
    then
        # Line has been moved; skip it.
        continue
    fi
    
    echo "$line"
done <<< "$diff_lines"

if [ "${line+defined}" = defined ]
then
    printf "$line"
fi
Run Code Online (Sandbox Code Playgroud)