如何使用sed将双引号前的换行符替换为空格?
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 calledafor our loopN: Takes the next line of the file and appends it to the current "pattern space" (sosedworks 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 labela—this repeats until every line is loaded into memorys/"\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

