如何过滤hosts文件中Reddit条目并写回原文件(适配动态更新)
Got it, let's fix this problem properly! The key issue here is that we can't rely on fixed line numbers since the hosts file updates regularly—so we need a way to dynamically target and remove the entire Reddit block (including the comment line and all associated 0.0.0.0 entries) without risking empty files or broken formatting.
Option 1: Use Awk (Safe & Cross-Platform)
Awk is perfect for pattern-based filtering, and using a temporary file ensures you won't accidentally wipe your hosts file if something goes wrong. Run this command:
awk ' /^# Reddit$/ { skip=1; next } skip && /^# / { skip=0; } !skip { print } ' ./hosts > hosts.tmp && mv hosts.tmp ./hosts
How this works:
- When we hit the exact line
# Reddit, we set askipflag to 1 and skip printing that line. - While
skipis active, as soon as we hit the next block's header (lines starting with#), we turn off theskipflag and resume printing. - All lines where
skipis 0 get printed to the temporary file. - Finally, we replace the original hosts file with the filtered temporary file only if the awk command succeeds—so your original file stays intact if there's an error.
Option 2: Use GNU Sed (Quick & Direct)
If you're on a Linux system with GNU Sed, you can modify the file in-place with a range-based delete command:
sed -i '/^# Reddit$/,/^# /{/^# Reddit$/!{/^# /!d;};}' ./hosts
Breakdown:
/^# Reddit$/,/^# /: Targets the range starting at the# Redditline and ending at the next line starting with#.{/^# Reddit$/!{/^# /!d;};}: Within that range, we delete all lines except the start of the next block's header—so we don't break the structured formatting of the hosts file.
Why Your Original Approach Didn't Work
Your command cat ./hosts | grep "# Reddit" -A10 | sed -e '1,11d' was only extracting the Reddit block and removing parts of it, not filtering the entire hosts file to exclude those lines. The methods above operate on the full file and safely remove only the unwanted block.
Critical Precaution: Back Up First!
Before modifying your hosts file, always make a backup to avoid accidental data loss:
cp ./hosts ./hosts.bak
内容的提问来源于stack exchange,提问作者Scyless

