如何修改 etc/hosts 中的行?在具有特定域的行的开头添加#?

如何修改 etc/hosts 中的行?在具有特定域的行的开头添加#?

我有一个主机文件,其中包含大约 15 行特定主机条目。

# Entry added by Automation所有这些主机条目都有条目中的文本。

例如:

10.122.123.124  file1.auto.test-json.abx.com    # Entry added by Automation
10.122.123.125  file2.auto.test-json.abx.com    # Entry added by Automation
10.122.123.126  file3.auto.test-json.abx.com    # Entry added by Automation
10.122.123.127  file4.auto.test-json.abx.com    # Entry added by Automation

我想在包含该行的开头添加“#”# Entry added by Automation或完全删除该行。

所需输出:

# 10.122.123.124  file1.auto.test-json.abx.com    # Entry added by Automation
# 10.122.123.125  file2.auto.test-json.abx.com    # Entry added by Automation
# 10.122.123.126  file3.auto.test-json.abx.com    # Entry added by Automation
# 10.122.123.127  file4.auto.test-json.abx.com    # Entry added by Automation

答案1

你可以用 sed 来做

它检查包含“自动化添加的条目”的行,然后用 # 替换行的开头

sed '/Entry added by Automation/ s/^/# /' -i /etc/hosts

答案2

如果您只想过滤掉所有包含该内容的行,可以使用带有 -'v' 选项的 'grep'。例如:

grep -v "# Entry added by Automation" /etc/hosts > /etc/hosts.new
mv /etc/hosts.new /etc/hosts

相关内容