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

如何过滤hosts文件中Reddit条目并写回原文件(适配动态更新)

Solution to Remove Reddit Entries from StevenBlack Hosts File

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 a skip flag to 1 and skip printing that line.
  • While skip is active, as soon as we hit the next block's header (lines starting with # ), we turn off the skip flag and resume printing.
  • All lines where skip is 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 # Reddit line 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:51:44