Issue
The problem
I have the following input file:
test.txt
This is a text2
This is a text3
This is a text4
This is a text5
START
This is a text1
END
This is a text6
This is a text7
This is a text8
This is a text9
I'd like to print the text between the START
and END
block with sed
to
practice with it a little bit but I'm so confused how to achieve that.
What I've tried
I tried the following commands:
cat $(test.txt) | sed -n -e '{/START/=},{/END/=}p'
I hoped here that the{/START/=}
and{/END/=}
blocks return the line numbers where theSTART
andEND
block are.cat $(test.txt) | sed -n -e '$(sed -n -e "/START/="),$(sed -n -e "/END/=")p'
I tried to get the line numbers of theSTART
andEND
blocks by embedding them into$(...)
.
I'm getting out of ideas.
What would you recommend to use for?
Anyways, I'm also wondering if using sed
is the best tool for this task. Do you
have any suggestions for other tools which suit more for this task? I'd like to
see an example as well, thanks!
Solution
sed -ne '/START/,/END/p' test.txt
Is the typical solution. This will apply the p
command to all lines between (and including) line that matches START until the line that matches END.
Excluding the start and end of the range is not very clean in sed. One approach is to explicitly match them:
sed -ne '/START/,/END/{/START/d; /END/d; p;}' test.txt
but for this particular use case it's probably cleaner to include those lines in the range of lines that are explicitly deleted:
sed -e '1,/START/d' -e '/END/,$d' test.txt
Answered By - William Pursell Answer Checked By - Senaida (WPSolving Volunteer)