linux - 在两个模式之间添加字符串 - sed

标签 linux bash sed

我正在寻找一个启动脚本,它将在两个模式之间添加一串文本。

8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2 instance-1.c.testenvio1.internal instance-1 **want to add string here** # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

我希望它看起来像这样:

8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2 instance-1.c.testenvio1.internal instance-1 104.197.247.254 instance1.com  # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

我正在使用以下 sed 命令,但它会在遇到第一个“instance-1”时插入我的字符串

sed -i 's/\<instance-1\>/& 104.197.247.254 instance1.com/' /etc/hosts


8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2 instance-1 104.197.247.254 instance1.com.c.testenvio1.internal instance-1  # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

最佳答案

也许对数据来源​​的一些了解在这里肯定有帮助。

# Added by Google 表明这些行包含有关 Google Compute Engine 实例的信息。更重要的是,它们是 Google 添加的行,幸运的是遵循了预定义的模式。

在那种情况下,像下面这样的东西会有所帮助

$ sed -Ei -- 's/([[:blank:]]+instance-1[[:blank:]]+)(#.*)$/\1 104.197.247.254 instance1.com \2/' /etc/hosts

输出

8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2-instance-1-c.testenvio1.internal instance-1   104.197.247.254 instance1.com # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

旁注:实际的空格数也被保留。

关于linux - 在两个模式之间添加字符串 - sed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48545690/

相关文章:

linux - 仅当其 ASCII 格式文件时,shell one-liner 才能对文件进行分类

sql - 从 DDL 文件中提取表名

python - 为什么 python 脚本抛出 AttributeError : 'module' object not found, 但在可执行文件时有效?

linux - 对 expr 用法的困惑

linux - 如何使用 Bash 将文本文件的最后一行读入变量?

linux - 我如何从我的 centos/tmp 目录中删除旧的 [er] 文件,除了某些仍在使用的文件?

linux - 如何在nginx配置中通过域和子域动态root

linux - 在 Linux 上使用列名 = 文件名将多个文件中的列添加到新文件

ruby-on-rails - 在 sed 之后更改并应用文本 .first

linux - 为什么 sed 会产生两条相同的线?