我需要一个 sed 或 awk 命令,而不是脚本:
1) 在文件中依次匹配 2 个字符串:
# This configuration option has an automatic default value.
# filter = [ "a|.*/|" ]
这是必需的,因为任何单个字符串都可以在文件中多次出现。 但是两个这样的连续字符串非常独特地匹配它们。
2) 在匹配的字符串之后插入/append 此文本行:
filter = ["a|sd.*|", "a|drbd.*|", "r|.*|"]
3) 在第一次匹配后停止处理并追加
因此,文本文件如下所示:
...
# filter = [ "a|^/dev/hda8$|", "r|.*/|" ]
#
# This configuration option has an automatic default value.
# filter = [ "a|.*/|" ]
# Configuration option devices/global_filter.
# Limit the block devices that are used by LVM system components.
# Because devices/filter may be overridden from the command line, it is
# not suitable for system-wide device filtering, e.g. udev and lvmetad.
# Use global_filter to hide devices from these LVM system components.
# The syntax is the same as devices/filter. Devices rejected by
# global_filter are not opened by LVM.
# This configuration option has an automatic default value.
# global_filter = [ "a|.*/|" ]
# Configuration option devices/types.
# List of additional acceptable block device types.
# These are of device type names from /proc/devices, followed by the
...
我需要这样的输出:
...
# filter = [ "a|^/dev/hda8$|", "r|.*/|" ]
#
# This configuration option has an automatic default value.
# filter = [ "a|.*/|" ]
filter = ["a|sd.*|", "a|drbd.*|", "r|.*|"]
# Configuration option devices/global_filter.
# Limit the block devices that are used by LVM system components.
# Because devices/filter may be overridden from the command line, it is
# not suitable for system-wide device filtering, e.g. udev and lvmetad.
# Use global_filter to hide devices from these LVM system components.
# The syntax is the same as devices/filter. Devices rejected by
# global_filter are not opened by LVM.
# This configuration option has an automatic default value.
# global_filter = [ "a|.*/|" ]
# Configuration option devices/types.
# List of additional acceptable block device types.
# These are of device type names from /proc/devices, followed by the
...
在 stackoverflow 上找到的多行 sed 示例中没有一个对我有用。
我尝试了本主题中的 F. Hauri 示例:Append a string after a multiple line match in bash
sed -e $'/^admin:/,/^$/{/users:/a\ NewUser\n}'
在匹配唯一单词时它工作正常,但在匹配连续文本行时不起作用,如下所示:
# This configuration option has an automatic default value.
# filter = [ "a|.*/|" ]
并且在 sed 表达式中添加 '0, 以在第一个匹配时停止在这种情况下不起作用。
更新了描述以更好地描述目标。
最佳答案
awk '
/^\s+\# This configuration option has an automatic default value\./{
found=1
}
found && !flag && /\s+\# filter = \[ \"a\|\.\*\/\|\" \]/{
flag=1
$0=$0 ORS ORS " filter = [\"a|sd.*|\", \"a|drbd.*|\", \"r|.*|\"]"
}
1
' test.conf > test.tmp && cp test.conf test.conf.bak && mv -f test.tmp test.conf
关于awk - 在多行匹配后追加文本行并在第一个多行匹配处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57973631/