Issue
How to delete all the lines between two pattern in file using sed.
Here pattern are //test
and //endtest
, file content:
blah blah blah
c
f
f
[
]
//test
all text to be deleted
line1
line2
xyz
amv
{
//endtest
l
dsf
dsfs
Expected result:
blah blah blah
c
f
f
[
]
//test
//endtest
l
dsf
dsfs
Solution
This is common feature of sed
sed '/^\/\/test$/,/^\/\/endtest/d'
As /
is used to bound regex, they have to be escaped, in regex.
If you want to keep marks (as requested):
sed '/^\/\/test$/,/^\/\/endtest/{//!d}'
Explanation:
Have a look at info sed
, search for sed address
-> Regexp Addresses
and Range Addresses
.
Enclosed by { ... }
, symbol //
mean any bound.
The empty regular expression '//' repeats the last regular expression match (the same holds if the empty regular expression is passed to the 's' command).
!
mean not
, then d
for delete line
Alternative: You could write:
sed '/^\/\/\(end\)\?test$/,//{//!d}'
or
sed -E '/^\/\/(end)?test$/,//{//!d}'
Will work same, but care, this could reverse effect if some extra pattern //endtest
may exist before first open pattern (//test
).
... All this was done, using GNU sed
4.4!
Under MacOS, BSD sed
Under MacOS, I've successfully dropped wanted lines with this syntax:
sed '/^\/\/test$/,/^\/\/endtest/{/^\/\/\(end\)\{0,1\}test$/!d;}'
or
sed -E '/^\/\/test$/,/^\/\/endtest/{/^\/\/(end)?test$/!d;}'
Answered By - F. Hauri