Reputation: 697
I have a pattern like the one below
Start
Hi
How
Are
You
End
Hi
Start
Hi
How
do
You
Do
End
I need the string between the first Start
and End
.
I don't want the strings between second Start
and End
.
Is there a way to do this?
Upvotes: 1
Views: 694
Reputation: 203169
sed is an excellent tool for simple substitutions on a single line. For anything else use awk:
$ awk '/End/{exit} found{print} /Start/{found=1}' file
Hi
How
Are
You
When the current line contains Start set the "found" flag. On the next line and every subsequent line the found flag is set so print that line. When a line containing "End" is seen, exit. All very simple and if necessary in future you can easily control whether Start, End, or both are printed just by moving the {} parts around:
$ awk '/End/{exit} /Start/{found=1} found{print}' file
Start
Hi
How
Are
You
$ awk 'found{print} /End/{exit} /Start/{found=1}' file
Hi
How
Are
You
End
$ awk '/Start/{found=1} found{print} /End/{exit}' file
Start
Hi
How
Are
You
End
or just set the found flag back to zero instead of exiting if you want all the segments between Start/End:
$ awk '/End/{found=0} found; /Start/{found=1}' file
Hi
How
Are
You
Hi
How
do
You
Do
If End can occur before Start as suggested in a comment, then just tweak the script to only test for End within the "found" block:
awk 'found{ if (/End/) exit; print } /Start/{ found=1 }' file
Upvotes: 2
Reputation: 58361
This might work for you (GNU sed):
sed -n '/Start/,${//!p;/End/q}' file
Upvotes: 2
Reputation: 47089
You could also do it with an ed
script:
<<< '/Start/+1,/End/-1p' | ed -s infile
Output:
Hi
How
Are
You
Upvotes: 1
Reputation: 65781
This seems to work for me:
sed -n '/Start/{:a;n;/End/q;p;ba}'
$ echo 'Start
Hi
How
Are
You
End
Hi
Start
Hi
How
do
You
Do
End' | sed -n '/Start/{:a;n;/End/q;p;ba}'
Hi
How
Are
You
Upvotes: 5