You have the right idea, a mini-state machine in awk , but you need small mods according to the following transcript:
pax> echo 'Hi I would like to print text between these patterns ' | awk ' /patterns/ { echo = 0 } /Hi / { gsub("^.*Hi ", "", $0); echo = 1 } { if (echo == 1) { print } }'
Or in a concise form:
awk '/patterns/{e=0}/Hi /{gsub("^.*Hi ","",$0);e=1}{if(e==1){print}}'
Result:
I would like to print text between these
upon request.
How it works is as follows. Initially, the variable echo 0 means that there will be no echo.
Each line is checked in turn. If it contains patterns , the echo is disabled.
If it contains Hi followed by a space, the echo is turned on and gsub used to change the line to get rid of everything to Hi .
Then regardless of whether the line is on (possibly changed) when the echo flag is on.
Boundary cases will now appear, such as:
- strings containing two occurrences of
Hi ; or - strings containing something in front of
patterns .
You did not indicate how they should be handled so that I would not worry, but the basic concept should be the same.
paxdiablo
source share