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

如何用sed保留首个含X310A000的两行表头,删除其余同类表头?

How to Retain the First Two-Line Header and Remove Duplicates in Sed

Let's break down your problem and fix that broken sed command step by step.

Your Scenario Recap

You have a text file from TN3270 output where a two-line header (starting with X310A000 on the first line of the header) repeats every 24 lines. You want to keep the first occurrence of this header (which isn't at the start of the file) and delete all subsequent ones. The command sed '/X310A000/{N;d}' $file works to delete all headers, but your custom command to preserve the first one throws a syntax error.

Why Your Original Command Failed

The error sed: -e expression #1, char 28: unknown command: '/' comes from invalid sed syntax in this part:

/X310A000/,$ /X310A000/{N;d}

Sed doesn't allow repeating an address range like this—once you specify /X310A000/,$, you need to follow it directly with a command, not another address matcher. Your logic was on the right track, but the syntax was incorrect.

Working Solutions

Option 1: GNU Sed (Supports Variables)

This uses a flag variable to track whether we've already kept the first header, making the logic straightforward:

sed '
/X310A000/{
    if (!seen) {
        # First header: print both lines and mark as seen
        seen=1
        p
        N
        p
    } else {
        # Subsequent headers: delete both lines
        N
        d
    }
}
# Print all non-header lines normally
p
' "$file"

Option 2: POSIX-Compliant Sed (Works on All Systems)

If you're using a non-GNU sed (like on macOS), use branch labels instead of variables for compatibility:

sed '
# When we hit the first X310A000, jump to print the header
/X310A000/{
    b print_first_header
}
# Print all non-matching lines
p
b end

# Branch to print the first header and set a skip flag
:print_first_header
p
N
p
# From here on, delete any matching headers
b skip_headers

:skip_headers
/X310A000/{
    N
    d
}
p

:end
' "$file"

How It Works

  1. First Header Handling: When we encounter the first X310A000, we print the current line, read the next line (with N), print that too, then switch to a mode where any future X310A000 matches trigger a delete of both lines.
  2. Non-Header Lines: All lines that don't start the header are printed normally throughout the process.

内容的提问来源于stack exchange,提问作者Joe Fruchey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:17:56