简体   繁体   中英

How to get text between two patterns in awk?

Giving this input.txt:

START asd
blah
blah
blah

START HELLO
lorem
ipsum
dolor 
sit
amet

START STACK
bleh
bleh

I'm trying to get the lines between START HELLO and START STACK .

So this is the desired output :

START HELLO
lorem
ipsum
dolor 
sit
amet

I did this awk:

awk '/START/{l++} {if(l==2){exit;} if(l==1) {print}}' input.txt

But returns the first START block, not the START HELLO :

START asd
blah
blah
blah

Do you have any idea to do it as clearer as possible? I've just started with awk few days ago, so any tip, help or advided will be appreciated.

The blank lines are handy: you can use "paragraph" mode where each awk record is separated by blank lines instead of newlines:

awk -v RS="" '/^START HELLO/' file

If the "hello" is to be passed in as a parameter:

awk -v RS="" -v start=HELLO '$1 == "START" && $2 == start' file

IF you need to specify between START HELLO and START STACK regardless of space paragraph:

awk '/START HELLO/ {f=1} /START STACK/ {f=0} f;' file
START HELLO
lorem
ipsum
dolor
sit
amet

It will be a more exact answer to the question: (and better if you need multiple sections)

I'm trying to get the lines between START HELLO and START STACK.   

I would normal go for solution from Glenn, but its not true to the question

awk -v RS="" '/^START HELLO/' file

Your indexing is off. Simply change your awk to:

awk '/START/{l++} {if(l==3){exit;} if(l==2) {print}}' input.txt

To print the empty-line-separated block that starts with "START HELLO":

awk -v RS= '/^START HELLO/' file

To print the text between "START HELLO" and the next line that starts with "START":

awk '/^START HELLO{f=1} f{if (/^START/) exit; else print}' file

To print the text between "START HELLO" and the next line that starts with "START STACK":

awk '/^START HELLO{f=1} f{if (/^START STACK/) exit; else print}' file

If you are every considering a solution that uses getline , it is probably the wrong approach so make sure you read http://awk.info/?tip/getline and fully understand the appropriate uses and all of the caveats before making a decision.

我认为这可能会解决您的问题:

awk '/START HELLO/{print;while(getline)if($0 !~/START STACK/)print;else exit}' input.txt

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