使用sed替换换行分隔的大括号失败,寻求可行解决方案
Got it, let's work through this sed problem you're stuck on. The biggest pain here is targeting only those newline-separated curly brace blocks without accidentally touching all the other lines that start with {—I totally get why generic fixes fell flat.
Let's Start with a Precise Sed Script
Assuming you're trying to replace entire blocks where { is on its own line, followed by any content, and ending with } on its own line (like the example below), here's a script that will only target those specific blocks:
# First, store your replacement text in a variable to avoid quoting headaches REPLACEMENT="Doesn't matter about \n I've tried this : but doesn't work. I've tried other strange solutions but don't work as well because in the file there are a lot of others rows that start with { . Could you please suggest some solution?" # Run the sed command sed -E ':loop; /^{$/{N; /\n}$/!b loop; s/.*\n.*$/'"$REPLACEMENT"'/}' yourfile.txt
How This Works (Breakdown)
Let's unpack what each part does so you can tweak it if needed:
:loop: Creates a label for looping through lines until we find the closing}/^{$/: Matches lines that contain only{(so it ignores lines like{ "data": 123 }that start with{but have other content)N: Reads the next line into the pattern space (combines the current line with the next)/\n}$/!b loop: If the combined lines don't end with a newline followed by}, jump back to thelooplabel to read another lines/.*\n.*$/'"$REPLACEMENT"'/: Replaces the entire matched block (from the opening{to closing}) with your desired text
Tweaks for Different Scenarios
If your target blocks don't have {/} on their own lines (e.g., { is at the start of a line with other text, but the closing } is on its own line), adjust the match pattern:
Change /^{$/ to /^{/ to match any line starting with {, but keep the rest of the script the same. Just note this might catch more blocks, so test it on a copy of your file first!
In-File Editing
To modify your file directly (instead of printing to stdout), add the -i flag (GNU sed):
sed -i -E ':loop; /^{$/{N; /\n}$/!b loop; s/.*\n.*$/'"$REPLACEMENT"'/}' yourfile.txt
For BSD sed (common on macOS), use -i '' instead:
sed -i '' -E ':loop; /^{$/{N; /\n}$/!b loop; s/.*\n.*$/'"$REPLACEMENT"'/}' yourfile.txt
Test First!
Always run the command without -i first to verify it's only replacing the blocks you want—no one wants to accidentally mess up a large file!
内容的提问来源于stack exchange,提问作者ClaudioM

