bash - 尝试从单个命令解析多个模式(使用 sed)

标签 bash sed posix

我有多个文件(markdown),用于生成不同的工件。对于其中一个工件,我需要解析以 # 开头的行以及模式之间的行 (:::注释 ->:::)。

示例文件

# Blah 

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. 

- one 
- two 
- three 

<!-- 
::: notes 

- one is yadda yadda 
- two is yadda yadda yadda 
- three is wrong 

:::
--> 

## derp derp 

Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

# woo hoo! 

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 

<!-- 
::: notes 

Aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

::: 
--> 

我可以使用 sed 为我找到所有 #

sed -n '/#/p' FILENAME.md

产生输出:

# Blah 
## derp derp 
# woo hoo! 

我可以使用 sed 正确查找并吐出注释

sed -n '/::: notes/, /:::/p' FILENAME.md 

产生输出:

::: notes 

- one is yadda yadda 
- two is yadda yadda yadda 
- three is wrong 

:::
::: notes

Aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

::: 

但我真正需要的是按照正确的顺序输出(与文件中出现的顺序相同),例如:

# Blah
::: notes 

- one is yadda yadda 
- two is yadda yadda yadda 
- three is wrong 

:::
## derp derp 
# woo hoo!
::: notes 

Aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

::: 

任何 sed 大师都可以使用吗? 提前致谢!!

最佳答案

可以通过这种方式指定多个搜索模式:

sed -e 'command' -e 'command' filename

所以你的解决方案将如下所示:

sed -n -e '/::: notes/, /:::/p' -e '/#/p' FILENAME.md

关于bash - 尝试从单个命令解析多个模式(使用 sed),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55307252/

相关文章:

bash - bin/activate 脚本的 "source"是什么意思?

linux - 尝试在 sed 中打印每行的一部分

python - 从 `which` 获取返回值来测试目录是否存在

c - POSIX 系统上的内存映射文件保持同步

c - 需要澄清有关 vfork 使用的信息

c - 一个 POSIX 兼容的操作系统通常会扩展 C 标准库的现有实现?

python - Bash 使用来自 Anaconda 的 Python,即使它已被停用

bash - 如何根据 bash 中的列变量解析输入

linux - 在模式前的文件名中添加字符串

linux - 删除日志文件中的重复行