I have a file something like:
# ID 1
blah blah
blah blah
$ description 1
blah blah
# ID 2
blah
$ description 2
blah blah
blah blah
How can I use a sed command to delete all lines between the #
and $
line? So the result will become:
# ID 1
$ description 1
blah blah
# ID 2
$ description 2
blah blah
blah blah
Can you please kindly give an explanation as well?
Use this sed command to achieve that:
sed '/^#/,/^\$/{/^#/!{/^\$/!d}}' file.txt
Mac users (to prevent extra characters at the end of d command
error) need to add semicolons before the closing brackets
sed '/^#/,/^\$/{/^#/!{/^\$/!d;};}' file.txt
# ID 1
$ description 1
blah blah
# ID 2
$ description 2
blah blah
blah blah
/^#/,/^\$/
will match all the text between lines starting with #
to lines starting with $
. ^
is used for start of line character. $
is a special character so needs to be escaped./^#/!
means do following if start of line is not #
/^$/!
means do following if start of line is not $
d
means deleteSo overall it is first matching all the lines from ^#
to ^\$
then from those matched lines finding lines that don't match ^#
and don't match ^\$
and deleting them using d
.