能否在Bash中按颜色解析icdiff输出以提取指定差异行?
Great question! I’ve used icdiff regularly, so I totally get what you’re going for—cutting through the partial-color lines to focus only on fully changed (pure red or pure green) content. Let’s walk through a few ways to solve this:
1. Parse ANSI Color Codes with Bash
icdiff uses standard ANSI escape codes for coloring:
- Pure red lines start with
\033[31m(foreground red) - Pure green lines start with
\033[32m(foreground green) - Partial-difference lines mix in other codes (like yellow
\033[33mfor changed segments)
You can use awk to filter lines that only use red/green and strip out the color codes for clean output:
icdiff old_file new_file | awk ' /^\033\[3[12]m/ && !/\033\[3[03-9]m/ { gsub(/\033\[[0-9;]*m/, ""); # Remove all ANSI color codes print } '
How this works:
- The first condition matches lines starting with pure red/green
- The second condition ensures no other color codes (like yellow for partial changes) are present
gsubstrips out all escape sequences so you get plain text output
2. Tweak icdiff to Reduce Noise
While icdiff doesn’t have a built-in filter for this, you can adjust its output to make parsing easier:
- Use
--width=YOUR_SCREEN_WIDTH(e.g.,--width=150) to minimize line wrapping, which avoids split color codes - Add
--no-boldto simplify the escape code structure (fewer extra codes to parse) - Use
--line-numbersto keep context, but still apply the above awk filter if needed
3. Alternative Tools for Direct Filtering
If parsing color codes feels fragile, here are simpler alternatives that let you extract full-changed lines directly:
- Standard
diff:
Extract lines unique to the old file (pure red equivalent):
Extract lines unique to the new file (pure green equivalent):diff --changed-group-format='%<' --unchanged-group-format='' old_file new_filediff --changed-group-format='%>' --unchanged-group-format='' old_file new_file - Git Diff (if working with version-controlled files):
Filter for added (A) and deleted (D) lines:git diff --diff-filter=AD --no-index old_file new_file - sdiff:
Filter lines marked as unique to left/right (matches icdiff’s pure red/green):sdiff old_file new_file | grep -E '^<|^>' | sed 's/^[<>] //'
Hope one of these approaches fits your workflow! The awk method is perfect if you want to stick with icdiff’s side-by-side coloring but only keep the fully changed lines, while the alternative tools offer more direct filtering without color parsing.
内容的提问来源于stack exchange,提问作者Joe Healey

