gpt4 book ai didi

sed - 使用 sed 在两个正则表达式之间打印行

转载 作者:行者123 更新时间:2023-12-04 00:01:42 25 4
gpt4 key购买 nike

我有一个包含多个部分的文本文件,我想打印其中一个部分。

文件的一部分看起来像

3. line 3
4. line 4

## Screenshots ##

1. line 1
2. line 2
3. line 3
4. line 4

## Changelog ##

3. line 3
4. line 4

从此我想检索 ## Screenshots ## 之间的所有行以及下一节的开始。这里下一节是 ## Changelog ## ,但它可以是任何东西。所以我们唯一可以依赖的是它会以 ## 开头。 .

来自 another thread ,我找到了以下代码
sed -e "H;/${pattern}/h" -e '$g;$!d' $file

我修改为
sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md

现在,它检索从 ## Screenshots ## 开始的所有行。 ,但它会打印所有行,直到文件末尾。

然后我把它用管道传送到另一个 sed喜欢
sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md | sed "/^##/q" 

但现在它只打印
## Screenshots ##

无论如何我可以打印屏幕截图部分的所有行吗?

最佳答案

awk '/pattern/{p=1;print;next} p&&/^##/{p=0};p' file

以“截图”为例:
kent$  awk '/^## Screenshot/{p=1;print;next} p&&/^##/{p=0};p' file
## Screenshots ##

1. line 1
2. line 2
3. line 3
4. line 4

编辑 添加说明
awk '/^## Screenshot/{p=1;print;next} : if match pattern, set p=1,print the line,read next line,(stop processing following scripts)
p&&/^##/{p=0} : if p==1 and match /##/ again (next section), set p=0
;p' file : if p==1, print the line

仅 sed
sed -n '/## Screensh/,/##/{/Scree/{p;n};/##/{q};p}' file

编辑2 向 sed cmd 添加说明
-n                 -> not print
'/## Screen/, /##/ -> match range, I guess you knew it already
{ -> if in this range
/Scree/ -> and line matches /Screenshot/
{p;n}; -> do print line, and read next row (skip doing rest processing)
/##/ -> if line matches "##"
q; -> quit, we have done all printing
p -> if we come to here, print the line
}

关于sed - 使用 sed 在两个正则表达式之间打印行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16587218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com