You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Bash中按颜色解析icdiff输出以提取指定差异行?

Filtering Pure Red/Green Lines from icdiff Output

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[33m for 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
  • gsub strips 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-bold to simplify the escape code structure (fewer extra codes to parse)
  • Use --line-numbers to 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):
    diff --changed-group-format='%<' --unchanged-group-format='' old_file new_file
    
    Extract lines unique to the new file (pure green equivalent):
    diff --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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:42:44