问题描述
我有一个包含多个部分的文本文件,我想打印其中一个部分.
I have a text file which contains multiple sections and I want to print one of those sections.
文件的一部分看起来像
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 ##
,但它可以是任何内容.所以我们唯一可以依赖的是它会以 ##
开头.
From this I want to retrieve all lines between ## Screenshots ##
and the starting of the next section. Here the next section is ## Changelog ##
, but it could be anything. So the only thing which we can depend on is that it will start with ##
.
从另一个线程,我找到了以下代码
sed -e "H;/${pattern}/h" -e '$g;$!d' $file
我修改为
sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md
现在,它检索从 ## Screenshots ##
开始的所有行,但它会打印所有行,直到文件末尾.
Now, it retrieves all lines starting from ## Screenshots ##
, but it prints all lines till the end of the file.
然后我把它传送到另一个 sed
就像
I then piped it to another sed
like
sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md | sed "/^##/q"
但现在只能打印
## Screenshots ##
无论如何我可以打印屏幕截图部分中的所有行吗?
Is there anyway I can print all lines in the screenshots section?
推荐答案
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
EDIT2 为 sed cmd 添加说明
EDIT2 add explanation to 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 在两个正则表达式之间打印行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!