regex - 使用 sed 查找模式包围的文本

标签 regex bash sed sh

我有一个像这样的配置文件:

[whatever]
Do I need this? no!

[directive]
This lines I want
Very much text here
So interesting

[otherdirective]
I dont care about this one anymore

现在我想匹配 [directive][otherdirective] 之间的行,而不匹配 [directive][其他指令]

此外,如果未找到[otherdirective],则应返回直到文件末尾的所有行。 [...] 可能包含任何数字或字母。

尝试

我使用 sed 尝试过此操作,如下所示:

sed -r '/\[directive\]/,/\[[[:alnum:]+\]/!d

此尝试的唯一问题是第一行是[directive],最后一行是[otherdirective]

我知道如何再次通过管道来截断第一行和最后一行,但是有 sed 解决方案吗?

最佳答案

您可以使用该范围,就像您尝试的那样,并在其中使用 // 取反。当它为空时,它会重用最后一个匹配的正则表达式,因此它将跳过两条边缘线:

sed -n '/\[directive\]/,/\[otherdirective\]/ { //! p }' infile

它产生:

This lines I want
Very much text here
So interesting

关于regex - 使用 sed 查找模式包围的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22329694/

相关文章:

bash - Mercurial:检查最后一次拉取/更新是否引入了更改

linux - 从 Git 获取单个文件版本

sed - 什么命令 `sed -i "s/^\+//g; s/\+/\t/g"` 是什么意思?

regex - sed 无法识别括号后的制表符

javascript - 无法确定可能是 stringA/stringB/StringX 或 stringA/stringX 而不仅仅是 stringA/stringB 的路径格式的正则表达式

regex - Postgres 正则表达式匹配 - 匹配一个字符或什么都不匹配

linux - 是否有任何快捷方式可以引用 MV 命令中第一个参数的路径?

javascript - 点后仅保留两位小数( Angular )

php - 使用正则表达式删除字符串的末尾部分

awk - 从文件中grep ip和端口