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

关于sed命令无法替换所有'day'匹配项的技术求助

Why isn't sed replacing all instances of 'day'?

Hey there! Let's get to the bottom of this sed issue you're facing.

The Root Cause

By default, sed's substitution command (s/pattern/replacement/) only replaces the first occurrence of the pattern on each line. That's why you're ending up with night night day instead of all nights—your command is missing the critical global replacement flag.

To align with your output: if your input was a single line like day day day, the default command would only swap the first day to night, giving night day day. Since you're seeing two replacements, maybe your input is split across two lines (e.g., day day on the first line, day on the second)? Even then, the default command would replace the first day on each line, resulting in night day and night—which doesn't match your output. No matter the exact input structure, the fix is the same.

The Correct Fix

To make sed replace every single occurrence of day (not just the first per line), add the g (global) flag to the end of your substitution command. Here's what that looks like:

sed 's/day/night/g' your_input_file.txt

Let's test this with your expected scenario:

  • Input: day day day
  • Run: echo "day day day" | sed 's/day/night/g'
  • Output: night night night

Perfect—this matches exactly what you wanted!

Quick Extra Note

If you ever need to replace patterns across multiple lines (a more advanced use case), you'd use flags like N to join lines, but for your current issue, adding the g flag is all you need to get every day swapped to night.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:07:34