简体   繁体   中英

Find text enclosed by patterns using sed

I have a config file like this:

[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

Now I want to match the lines in between [directive] and [otherdirective] without matching [directive] or [otherdirective] .

Also if [otherdirective] is not found all lines till the end of file should be returned. The [...] might contain any number or letter.

Attempt

I tried this using sed like this:

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

The only problem with this attempt is that the first line is [directive] and the last line is [otherdirective] .

I know how to pipe this again to truncate the first and last line but is there a sed solution to this?

You can use the range, as you were trying, and inside it use // negated. When it's empty it reuses last regular expression matched, so it will skip both edge lines:

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

It yields:

This lines I want
Very much text here
So interesting

Here is a nice way with awk to get section of data.

awk -v RS= '/\[directive\]/' file
[directive]
This lines I want
Very much text here
So interesting

When setting RS to nothing RS= it divides the file up in records based on blank line.
So when searching for [directive] it will print that record.
Normally a record is one line, but due to the RS (record selector) is change, it gives the block.

Okay damn after more tries I found the solution or merely one solution:

sed -rn '/\[buildout\]/,/\[[[:alnum:]]+\]/{
    /\[[[:alnum:]]+\]/d
    p }'

is this what you want?

\[directive\](.*?)\[

Look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM