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

如何使用sed将双引号前的换行符替换为空格?

Sed: Replace Newlines After Double Quotes with Spaces

Hey there! Let's fix that sed task you're working on. You want to swap out only those newlines that come right after a double quote (your phrasing of "newlines before a double quote" makes sense too—we're targeting the same pattern) with a regular space, leaving all other newlines as-is.

What You're Trying to Do

Here's your example, clarified:

Original content (note the newline after colorSchemeMapping):

<link rel="colorSchemeMapping 
href="marinedrugs-790193-original.fld/colorschememapping.xml">

Target content (newline replaced with space):

<link rel="colorSchemeMapping" href="marinedrugs-790193-original.fld/colorschememapping.xml">

The Solution Command

You already know the handy sed trick to load the whole file into memory (:a;N;$!ba)—that's crucial here because we need to match a pattern that spans two lines. We just need to tweak the substitution to target exactly the newlines we care about.

Here's the adjusted command:

sed ':a;N;$!ba;s/"\n/" /g' your-file.txt

Let's Break This Down

I'll walk through each part so you know exactly what's going on:

  • :a : Sets up a label called a for our loop
  • N : Takes the next line of the file and appends it to the current "pattern space" (so sed works with the whole file instead of one line at a time)
  • $!ba : If we haven't reached the last line ($! means "not the last line"), jump back to label a—this repeats until every line is loaded into memory
  • s/"\n/" /g : The magic part! This globally replaces every instance of a double quote followed by a newline ("\n) with a double quote followed by a space (" ). Exactly what you need—only replaces newlines that come right after a quote.

Quick Bonus Tip

If you want to edit the file directly (instead of just printing changes to your terminal), add the -i flag. On macOS, use -i.bak to create a backup of the original file before modifying it:

# Linux
sed -i ':a;N;$!ba;s/"\n/" /g' your-file.txt

# macOS
sed -i.bak ':a;N;$!ba;s/"\n/" /g' your-file.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:32:31