Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print lines between two regex using sed

Tags:

unix

sed

I have a text file which contains multiple sections and I want to print one of those sections.

Part of the file looks like

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

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 ##.

From another thread, I found the following code

sed -e "H;/${pattern}/h" -e '$g;$!d' $file

which I modified to

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

Now, it retrieves all lines starting from ## Screenshots ##, but it prints all lines till the end of the file.

I then piped it to another sed like

sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md | sed "/^##/q" 

But now it prints only

## Screenshots ##

Is there anyway I can print all lines in the screenshots section?

like image 576
Sudar Avatar asked May 16 '13 12:05

Sudar


1 Answers

sed -n '/## Screenshots ##/,/##/p' readme.md

This will start printing from ## Screenshots ## till the next ## is found. If you don't want the last ## match, easiest is

sed -n '/## Screenshots ##/,/##/p' readme.md |head -n-1

like image 59
abasu Avatar answered Sep 30 '22 16:09

abasu