This post goes over how to delete lines between two patterns with sed:
This post was inspired by Sed: Mutli-Line Replacement Between Two Patterns. See related post Sed replace lines between two patterns.
Inclusive
Delete lines between 2 patterns (inclusive):
sed "/$PATTERN1/,/$PATTERN2/d" $FILE
Replace
$PATTERN1with your 1st pattern,$PATTERN2with your 2nd pattern, and$FILEwith your file path.
Example
Given file file.txt:
one
two
three
four
five
Remove lines between two and four (inclusive):
sed '/two/,/four/d' file.txt
Output:
one
five
Write the output to the same file (macOS):
sed -i '' '/two/,/four/d' file.txt
On Linux, remove the
''after-i.
Exclusive
Delete lines between 2 patterns (exclusive):
sed "/$PATTERN1/,/$PATTERN2/{/$PATTERN1/n;/$PATTERN2/!d;}" $FILE
Replace
$PATTERN1with your 1st pattern,$PATTERN2with your 2nd pattern, and$FILEwith your file path.
Example
Given file file.txt:
one
two
three
four
five
Remove lines between two and four (exclusive):
sed '/two/,/four/{/two/n;/four/!d;}' file.txt
Output:
one
two
four
five
Write the output to the same file (macOS):
sed -i '' '/two/,/four/{/two/n;/four/!d;}' file.txt
On Linux, remove the
''after-i.