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

如何用sed删除含#但不含Chris或Ana的行及其下一行?

Got it, let's sort this out for you. You want to strip out any lines that contain a # but don't include either Chris or Ana—and also remove the line immediately following those matching lines. Here are two practical solutions depending on your workflow:

1. Python Script (Cross-Platform, Easy to Adjust)

This approach is straightforward and works on any system with Python installed. It explicitly tracks which lines to keep or skip:

# Paste your input text here, or read from a file
input_content = """#Hello my name is Chris next line of random txt
#Hello my name is Bob next line of random txt
Hello Ana is my name # next line of random txt
Another Line
"""

lines = input_content.splitlines()
result = []
skip_next_line = False

for line in lines:
    if skip_next_line:
        skip_next_line = False
        continue
    # Check if the line has a # but no Chris/Ana
    if "#" in line and "Chris" not in line and "Ana" not in line:
        skip_next_line = True
        continue
    result.append(line)

# Print or write the output
final_output = "\n".join(result)
print(final_output)

When you run this, it’ll output exactly what you’re looking for:

#Hello my name is Chris next line of random txt
Hello Ana is my name # next line of random txt
Another Line

2. Sed Command (Linux/macOS Terminal)

If you prefer using command-line tools, this sed command uses extended regex to target the lines you want to remove:

sed -E '/#(?!.*(Chris|Ana))/{n; d;}' input.txt
  • The regex /#(?!.*(Chris|Ana))/ matches any line with a # that doesn’t contain Chris or Ana.
  • {n; d;} tells sed to read the next line (n) and delete both the matching line and the following one (d).
  • All other lines are printed automatically.

Just replace input.txt with your actual file name, and it’ll spit out the filtered content.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:18:12