sed:如何删除以注释行为界的文件中的行范围?

问题描述 投票:0回答:2

示例文件:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost
# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
# <docker-registry>
docker.local 127.0.0.1
# </docker-registry>

使用sed(https://unix.stackexchange.com/a/236754)的范围表达式功能,我想删除以下几行:

# <docker-registry>
docker.local 127.0.0.1
# </docker-registry>

在尝试了不同的语法之后,这是我能想到的最好的方法:

sed -n 's|# <docker-registry>|,|# </docker-registry>|p' $FILE

没有s标志,出现以下错误:

sed: 1: "|# <docker-registry>|,| ...": invalid command code |

使用s标志,出现以下错误:

sed: 1: "s|# <docker-registry>|, ...": bad flag in substitute command: '#'

如何获得所需的结果?

sed
2个回答
0
投票

我在发布问题时找到了答案,所以出于后验:

  1. 为了从sed输出中删除行,请在表达式的末尾添加d标志:

sed -n 's|# <docker-registry>|,|# </docker-registry>|d' $FILE

  1. sed产生流。为了覆盖文件,将结果通过管道传递到文件:

sed -n 's|# <docker-registry>|,|# </docker-registry>|d' $FILE > $FILE

  1. 可以通过使用默认的分隔符并在结束模式中转义/来避免sed: 1: "s|# <docker-registry>|, ...": bad flag in substitute command: '#'错误:

sed '/# <docker-registry>/,/# <\/docker-registry>/d' $FILE > $FILE

你去了:)


0
投票

您将在标准输出上收到结果:

sed -e '/# <docker-registry>/,/# <\/docker-registry>/d' yourdatafile

如果需要编辑数据文件,请使用ed而不是sed。编剧:

/# <docker-registry>/,/# <\/docker-registry>/d
w
q

电话:

ed yourdatafile <script.ed
© www.soinside.com 2019 - 2024. All rights reserved.